Compare commits

...
3 Commits
Author SHA1 Message Date
sudacode 727be5683a fix(youtube): keep mpv queue when advancing to a queued video on Windows (#281) 2026-10-02 22:13:35 -07:00
sudacode 138bfe9759 fix(subtitles): allow Whisper generation during Windows YouTube stream playback (#282) 2026-10-02 22:13:15 -07:00
sudacode 0aba17d95b chore(release): generate concise release notes per feature or area
- Rewrite polish prompt to default to inline items, nesting only for several distinct changes
- Add length/density example and drop internal details from release bodies
- Tell prerelease mode to shorten long baseline bullets
- Update changes/README.md and prompt assertions in tests
2026-10-02 19:52:16 -07:00
13 changed files with 363 additions and 48 deletions

No files matched your search

+1 -1
View File
@@ -42,7 +42,7 @@ How fragments turn into a release:
- At release time, `bun run changelog:build` (and `bun run changelog:prerelease-notes`) pipes every pending fragment through `claude -p` to merge related items, drop noise, and rewrite into a clean user-facing release body. Write fragments as raw, informative notes — don't worry about polished prose, deduping across PRs, or line-by-line phrasing. The polish step handles all of that.
- The polish step treats pending fragments as the final release outcome, not prerelease history. If a feature is added and then renamed or fixed before the stable cut, ship the final feature bullet instead of separate prerelease-only breaking/fix entries.
- `CHANGELOG.md`, GitHub release notes, and prerelease notes all use short top-level items with one nested bullet per distinct change, instead of packing a release's worth of detail into a single paragraph bullet. An item with only one thing to say stays inline on the top-level bullet. Release notes and prerelease notes additionally cover user benefit and any useful action note in their nested bullets.
- `CHANGELOG.md`, GitHub release notes, and prerelease notes all use one item per feature or area, inline by default: `- **Name**: one or two short sentences.` Items with several separate changes may use a few short nested bullets instead of a run-on sentence. Items say what changed and how to reach it; implementation details, edge cases, and step-by-step usage belong in the docs, not the release body.
- `internal` fragments stay in `CHANGELOG.md` (inside a collapsed `<details>` block) but are dropped from the GitHub release notes entirely.
- The polished `CHANGELOG.md` and `release/release-notes.md` are committed and reviewed before tagging — edit the Markdown by hand if Claude misses something.
+4
View File
@@ -0,0 +1,4 @@
type: internal
area: release
- Release notes, prerelease notes, and `CHANGELOG.md` are now generated as short items per feature or area, nesting only when an item has several separate changes.
@@ -0,0 +1,4 @@
type: fixed
area: youtube
- The subtitle generation modal now works during Windows YouTube playback, where mpv plays a resolved stream URL instead of the YouTube page; it no longer asks you to open a local file or YouTube video, and generated subtitles load into the playing video.
@@ -0,0 +1,4 @@
type: fixed
area: youtube
- Fixed Windows YouTube playback dropping the rest of mpv's queue when it advanced to a video queued from the YouTube browser window. The direct stream now replaces only that playlist entry.
+12 -17
View File
@@ -44,20 +44,12 @@ function fragmentTypesInPrompt(input: string): string[] {
.map((line) => line.slice('type: '.length).trim());
}
function assertPromptRequestsNestedBullets(input: string): void {
assert.match(input, /In both modes, split every item into one nested bullet per distinct change/);
assert.match(input, /Never stack several distinct changes into one long paragraph-shaped bullet/);
assert.match(input, /Keep nested bullets short, concrete, and readable by non-technical users/);
assert.match(input, /Avoid paragraph-style release-note bullets/);
}
function assertReleaseNotesPromptRequestsNestedBullets(input: string): void {
assertPromptRequestsNestedBullets(input);
assert.match(
input,
/In MODE: release-notes, nested bullets should also cover user benefit and any user action/,
);
assert.match(input, /Do not require the exact nested labels/);
function assertPromptRequestsConciseItems(input: string): void {
assert.match(input, /Default to inline/);
assert.match(input, /Use nested bullets only when an item has several distinct changes/);
assert.match(input, /Never write paragraph-length bullets/);
assert.match(input, /Merge aggressively: one item per feature or area/);
assert.match(input, /Release notes summarize; the docs hold the details/);
}
function defaultPolishedBody(input: string): string {
@@ -454,14 +446,13 @@ test('writeChangelogArtifacts prompts Claude to summarize the final stable outco
prompt,
/Multiple fixes within the same prerelease cycle should collapse into one current-state bullet/,
);
assertPromptRequestsNestedBullets(prompt);
assertPromptRequestsConciseItems(prompt);
}
const releaseNotesPrompt = stub.calls.find(
(call) => modeFromPrompt(call.input) === 'release-notes',
);
assert.ok(releaseNotesPrompt, 'expected a release-notes Claude invocation');
assertReleaseNotesPromptRequestsNestedBullets(releaseNotesPrompt.input);
} finally {
fs.rmSync(workspace, { recursive: true, force: true });
}
@@ -817,7 +808,11 @@ test('writePrereleaseNotesForVersion prompts Claude to revise stale prerelease b
prompt,
/Multiple fixes within the same prerelease cycle should collapse into one current-state bullet/,
);
assertReleaseNotesPromptRequestsNestedBullets(prompt);
assert.match(
prompt,
/shorten long baseline bullets and collapse nested lists that do not need to be nested/,
);
assertPromptRequestsConciseItems(prompt);
} finally {
fs.rmSync(workspace, { recursive: true, force: true });
}
+24 -16
View File
@@ -476,21 +476,29 @@ You will receive a list of FRAGMENT entries below. Each fragment has metadata (t
</details>
Do not include the Internal section at all in MODE: release-notes; internal fragments will not be present in the input for that mode.
4. Each top-level change item should:
- Lead with a short feature/area name in title case. Pick the name from the fragment's bullet content, not the raw 'area:' slug.
- Be written in user-facing language. Drop implementation jargon, internal class names, file paths, and PR numbers.
- Be merged with related bullets when possible. If five fragments all touch Windows overlay z-order/focus/restore, write one or two bullets that summarize the overall improvement instead of five.
4. Start every item with a short bold feature/area name in title case and a colon. Pick the name from the fragment's bullet content, not the raw 'area:' slug.
- Default to inline: put one or two short sentences right after the colon. If the important details fit in two short sentences, stay inline.
- Use nested bullets only when an item has several distinct changes a user would care about separately and inline text would turn into a long run-on sentence. Then leave the top-level bullet as just the name and indent two to four nested bullets by two spaces.
- Each nested bullet is a single short sentence, roughly 20 words or fewer. Never write paragraph-length bullets. Cut minor details rather than adding sentences.
5. Keep items brief. Release notes summarize; the docs hold the details.
- Say what changed for the user and how to reach it (shortcut, command, setting, or menu). Stop there.
- Leave out how it works internally, edge cases, precedence rules, defaults, fallbacks, tool discovery, migration mechanics, and step-by-step usage.
- Name a config key only when users must set it to use the change or to keep their current behavior.
- Write in user-facing language. Drop implementation jargon, internal class names, file paths, and PR numbers.
- Merge aggressively: one item per feature or area. If five fragments touch Jellyfin subtitles, audio, and auth, write one Jellyfin item, not five. Group small unrelated fixes for the same area into one item.
- Drop bullets that only describe PR housekeeping, CodeRabbit follow-ups, or test-only changes that don't affect users.
- Preserve the substance of breaking changes that remain breaking after applying the Release Outcome Rules. Do not soften or omit them.
5. In both modes, split every item into one nested bullet per distinct change. Write a short bold name on the top-level bullet, then indent the details two spaces:
- **Playlist Browser**:
- Saved shows now open without rescanning the library.
- The picker remembers the last folder you browsed between launches.
Each nested bullet covers exactly one change, behavior, or user-visible outcome. Never stack several distinct changes into one long paragraph-shaped bullet.
Aim for two to five nested bullets per item. When an item genuinely has only one thing to say, put it inline on the top-level bullet ("- **Playlist Browser**: Saved shows now open without rescanning the library.") instead of emitting a single nested bullet.
Keep nested bullets short, concrete, and readable by non-technical users. Avoid paragraph-style release-note bullets.
Bullets inside the Internal section may stay single-level.
6. In MODE: release-notes, nested bullets should also cover user benefit and any user action or compatibility note when useful. Do not require the exact nested labels; natural phrasing is fine. Omit the action bullet when no action is needed.
- Preserve the substance of breaking changes that remain breaking after applying the Release Outcome Rules, including any action users must take. Do not soften or omit them.
6. Match the length and density of this example:
### Added
- **Subtitle Selection Modal**: Optional modal for picking primary and secondary subtitle tracks. Enable it in Settings under Behavior, then press g followed by s.
### Changed
- **Faster Sync**: Sync between macOS and Linux machines now uses compressed, incremental rsync transfers. Windows and machines without rsync fall back to compressed scp.
### Fixed
- **Subtitle Sidebar**: Space keeps its playback action after clicking a cue, and the sidebar no longer jumps away from the current position during subtitle gaps.
- **Jellyfin 12**:
- Playback, subtitles, artwork, and "Play on SubMiner" now work on Jellyfin 12.
- Casting no longer drops after about a minute.
- Mined cards get the episode title again.
7. Do not invent features. Every bullet must be grounded in the input fragments.
8. Do not include the version heading (## v...) — that wrapper is added by the caller.
@@ -791,7 +799,7 @@ function polishFragmentsWithClaude(
? [
'## Existing Prerelease Notes',
'',
'The input includes EXISTING PRERELEASE NOTES before the fragment list. Existing prerelease notes are a baseline, not an immutable changelog. Reuse reviewed highlight bullets when they still describe the current outcome, but replace stale beta or RC wording when new fragments supersede it. Merge in only new or changed fragment material, and deduplicate instead of restating existing bullets. Output only the final highlights body using the section headings above; do not include the prerelease disclaimer, any "Changes since" section, or the Installation or Assets sections.',
'The input includes EXISTING PRERELEASE NOTES before the fragment list. Existing prerelease notes are a baseline, not an immutable changelog. Reuse reviewed highlight bullets when they still describe the current outcome, but replace stale beta or RC wording when new fragments supersede it. Merge in only new or changed fragment material, and deduplicate instead of restating existing bullets. The output rules above win over the baseline format: shorten long baseline bullets and collapse nested lists that do not need to be nested. Output only the final highlights body using the section headings above; do not include the prerelease disclaimer, any "Changes since" section, or the Installation or Assets sections.',
'',
].join('\n')
: '';
@@ -814,7 +822,7 @@ Rules:
3. ADDED fragments describe changes that are new in this build; summarize them.
4. MODIFIED fragments include BEFORE and AFTER content. Describe only the behavioral difference between them. If the edit is editorial (rewording, deduplication, reformatting, reconciling stale phrasing) with no user-visible behavior change, omit it entirely.
5. DELETED fragments mean the described change was removed or reverted before this build; say so explicitly.
6. Keep bullets short and concrete. Use nested bullets sparingly.
6. Keep each bullet to one short, concrete sentence. Use nested bullets sparingly.
7. Do not invent changes. Every bullet must be grounded in the diffs.
8. If no bullet survives rules 2-5, output exactly this single line:
- No user-facing changes since PREVIOUS_TAG.
+2
View File
@@ -6818,6 +6818,8 @@ const subtitleGenerationRuntime = createSubtitleGenerationRuntime({
'youtube-whisper.ja.srt',
),
}),
resolveYoutubeSourceUrl: (mediaPath) =>
youtubePlaybackRuntime.getYoutubeSourceUrlForStream(mediaPath),
getMpvClient: () => appState.mpvClient,
onProgress: (progress) => {
for (const window of [overlayManager.getMainWindow(), overlayManager.getModalWindow()]) {
@@ -368,7 +368,10 @@ test('cancelling a YouTube Whisper job resolves to null, and failures throw', as
);
});
function youtubeFixture(generateYoutube: SubtitleGenerationRuntimeDeps['generateYoutube']) {
function youtubeFixture(
generateYoutube: SubtitleGenerationRuntimeDeps['generateYoutube'],
overrides: Partial<SubtitleGenerationRuntimeDeps> = {},
) {
const player = {
path: 'https://www.youtube.com/watch?v=abcdefghijk&pp=search',
paused: false,
@@ -385,7 +388,7 @@ function youtubeFixture(generateYoutube: SubtitleGenerationRuntimeDeps['generate
return { error: 'success' };
},
};
const { runtime } = fixture({ getMpvClient: () => client, generateYoutube });
const { runtime } = fixture({ getMpvClient: () => client, generateYoutube, ...overrides });
return { runtime, player, commands };
}
@@ -443,3 +446,63 @@ test('switching videos cancels a YouTube job from the modal without loading its
false,
);
});
// Windows plays YouTube through a resolved googlevideo stream, so mpv's path is not a YouTube URL.
const STREAM_URL = 'https://rr1---sn.example.googlevideo.com/videoplayback?expire=1777777777';
const OTHER_STREAM_URL = 'https://rr2---sn.example.googlevideo.com/videoplayback?expire=1888888888';
const resolveStreamSource = (mediaPath: string): string | null =>
mediaPath === STREAM_URL
? 'https://www.youtube.com/watch?v=abcdefghijk'
: mediaPath === OTHER_STREAM_URL
? 'https://www.youtube.com/watch?v=zyxwvutsrqp'
: null;
test('the modal generates for a YouTube video playing through a resolved stream URL', async () => {
let jobSignal: AbortSignal | null = null;
const { runtime, player, commands } = youtubeFixture(
async (input) => {
jobSignal = input.signal;
assert.equal(input.url, 'https://www.youtube.com/watch?v=abcdefghijk');
// Reloading the same video's stream must not cancel the job.
runtime.handleMediaPathChange(STREAM_URL);
return '/tmp/subs/youtube-whisper.ja.srt';
},
{ resolveYoutubeSourceUrl: resolveStreamSource },
);
player.path = STREAM_URL;
assert.equal(
(await runtime.getStatus()).mediaPath,
'https://www.youtube.com/watch?v=abcdefghijk',
);
assert.deepEqual(await runtime.start(), {
ok: true,
outputPath: '/tmp/subs/youtube-whisper.ja.srt',
message: 'Japanese subtitles generated and loaded.',
});
assert.equal((jobSignal as AbortSignal | null)?.aborted, false);
assert.deepEqual(
commands.find((command) => command[0] === 'sub-add'),
['sub-add', '/tmp/subs/youtube-whisper.ja.srt', 'select', 'Generated Japanese', 'ja'],
);
});
test('switching to another resolved YouTube stream cancels the modal job', async () => {
let jobSignal: AbortSignal | null = null;
const { runtime, player } = youtubeFixture(
(input) =>
new Promise((_, reject) => {
jobSignal = input.signal;
input.signal.addEventListener('abort', () => reject(new Error('Aborted')), { once: true });
}),
{ resolveYoutubeSourceUrl: resolveStreamSource },
);
player.path = STREAM_URL;
const job = runtime.start();
while (!jobSignal) await new Promise((resolve) => setImmediate(resolve));
player.path = OTHER_STREAM_URL;
runtime.handleMediaPathChange(player.path);
assert.deepEqual(await job, { ok: false, message: 'Cancelled.' });
});
@@ -51,6 +51,11 @@ export interface SubtitleGenerationRuntimeDeps {
signal: AbortSignal;
onProgress: (progress: SubtitleGenerationProgress) => void;
}) => Promise<string>;
/**
* Maps a playing stream URL back to its YouTube page URL. Windows YouTube playback opens a
* resolved direct stream in mpv, so mpv's path alone does not identify the video.
*/
resolveYoutubeSourceUrl?: (mediaPath: string) => string | null;
}
async function currentLocalMedia(client: GenerationMpvClient | null): Promise<string | null> {
@@ -62,12 +67,6 @@ async function currentLocalMedia(client: GenerationMpvClient | null): Promise<st
return typeof directory === 'string' ? path.resolve(directory, media) : null;
}
async function currentYoutubeMedia(client: GenerationMpvClient | null): Promise<string | null> {
if (!client?.connected) return null;
const media = await client.requestProperty('path');
return typeof media === 'string' ? toYoutubeWatchUrl(media) : null;
}
async function loadGeneratedSubtitles(client: GenerationMpvClient, outputPath: string) {
const loaded = await client.request([
'sub-add',
@@ -136,6 +135,15 @@ export function createSubtitleGenerationRuntime(deps: SubtitleGenerationRuntimeD
: '',
};
}
// The YouTube page behind a resolved stream URL, or the media path itself.
function youtubeSource(mediaPath: string | null | undefined): string | null | undefined {
return (mediaPath && deps.resolveYoutubeSourceUrl?.(mediaPath)) || mediaPath;
}
async function currentYoutubeMedia(client: GenerationMpvClient | null): Promise<string | null> {
if (!client?.connected) return null;
const media = await client.requestProperty('path');
return typeof media === 'string' ? toYoutubeWatchUrl(youtubeSource(media)) : null;
}
const report = (update: SubtitleGenerationProgress) => {
progress = update;
deps.onProgress(update);
@@ -246,7 +254,7 @@ export function createSubtitleGenerationRuntime(deps: SubtitleGenerationRuntimeD
/** Stops a YouTube job once its video is no longer playing, which also deletes its audio. */
handleMediaPathChange(mediaPath: string | null | undefined): void {
if (!youtubeJobUrl) return;
if (extractYoutubeVideoId(mediaPath) !== extractYoutubeVideoId(youtubeJobUrl))
if (extractYoutubeVideoId(youtubeSource(mediaPath)) !== extractYoutubeVideoId(youtubeJobUrl))
controller?.abort();
},
async setVadEnabled(enabled: boolean): Promise<SubtitleGenerationStatus> {
@@ -298,3 +298,116 @@ test('prepare youtube playback accepts a fresh-start path change when the direct
'replace',
]);
});
test('prepare youtube playback swaps a queued entry for its direct stream without clearing the playlist', async () => {
const commands: Array<Array<string>> = [];
const directUrl = 'https://rr16---sn.example.googlevideo.com/videoplayback?id=abc';
const observedPaths = ['https://www.youtube.com/watch?v=queued2', directUrl];
let requestCount = 0;
const prepare = createPrepareYoutubePlaybackInMpvHandler({
requestPath: async () => {
const value = observedPaths[Math.min(requestCount, observedPaths.length - 1)] ?? null;
requestCount += 1;
return value;
},
requestProperty: async (name) => {
if (name === 'playlist') {
return [
{ filename: 'https://www.youtube.com/watch?v=queued1' },
{ filename: 'https://www.youtube.com/watch?v=queued2', current: true, playing: true },
{ filename: 'https://www.youtube.com/watch?v=queued3' },
];
}
if (name === 'track-list') return [{ type: 'video', id: 1 }];
return null;
},
sendMpvCommand: (command) => commands.push(command),
wait: createWaitStub(),
});
const ok = await prepare({
url: directUrl,
sourceUrl: 'https://www.youtube.com/watch?v=queued2',
timeoutMs: 1500,
pollIntervalMs: 1,
});
assert.equal(ok, true);
assert.deepEqual(commands.slice(4), [
['loadfile', directUrl, 'append'],
['playlist-move', '3', '2'],
['playlist-remove', '1'],
]);
});
test('prepare youtube playback replaces the playlist when the current entry is a different video', async () => {
const commands: Array<Array<string>> = [];
const directUrl = 'https://rr16---sn.example.googlevideo.com/videoplayback?id=abc';
let nowTick = 0;
const prepare = createPrepareYoutubePlaybackInMpvHandler({
requestPath: async () => 'https://www.youtube.com/watch?v=other',
requestProperty: async (name) => {
if (name === 'playlist') {
return [
{ filename: 'https://www.youtube.com/watch?v=other', current: true, playing: true },
];
}
return [];
},
sendMpvCommand: (command) => commands.push(command),
wait: createWaitStub(),
now: () => {
nowTick += 100;
return nowTick;
},
});
await prepare({
url: directUrl,
sourceUrl: 'https://www.youtube.com/watch?v=picked',
timeoutMs: 200,
pollIntervalMs: 1,
});
assert.deepEqual(commands.slice(4), [['loadfile', directUrl, 'replace']]);
});
test('prepare youtube playback does not touch the playlist when the playing entry is another video', async () => {
const commands: Array<Array<string>> = [];
const directUrl = 'https://rr16---sn.example.googlevideo.com/videoplayback?id=abc';
let nowTick = 0;
const prepare = createPrepareYoutubePlaybackInMpvHandler({
// mpv's path still reports the queued video, but it is mid-advance: the selected entry moved
// on and the playing entry is another queued video.
requestPath: async () => 'https://www.youtube.com/watch?v=queued2',
requestProperty: async (name) => {
if (name === 'playlist') {
return [
{ filename: 'https://www.youtube.com/watch?v=queued1', playing: true },
{ filename: 'https://www.youtube.com/watch?v=queued2', current: true },
{ filename: 'https://www.youtube.com/watch?v=queued3' },
];
}
return [];
},
sendMpvCommand: (command) => commands.push(command),
wait: createWaitStub(),
now: () => {
nowTick += 100;
return nowTick;
},
});
await prepare({
url: directUrl,
sourceUrl: 'https://www.youtube.com/watch?v=queued2',
timeoutMs: 200,
pollIntervalMs: 1,
});
assert.equal(
commands.some((command) => command[0] === 'playlist-remove'),
false,
);
assert.deepEqual(commands.slice(4), [['loadfile', directUrl, 'replace']]);
});
+59 -1
View File
@@ -2,6 +2,11 @@ import { isYoutubeMediaPath } from './youtube-playback';
type YoutubePlaybackLaunchInput = {
url: string;
/**
* YouTube page URL `url` was resolved from (Windows loads a direct stream URL). Lets a playlist
* entry for the same video be swapped in place instead of replacing the whole playlist.
*/
sourceUrl?: string;
timeoutMs?: number;
pollIntervalMs?: number;
};
@@ -81,6 +86,52 @@ function hasPlayableMediaTracks(trackListRaw: unknown): boolean {
});
}
/** Index of the entry mpv is actually playing, or null while it is between entries. */
function findPlayingPlaylistEntry(playlist: unknown[]): { index: number; filename: string } | null {
const index = playlist.findIndex(
(entry) =>
typeof entry === 'object' &&
entry !== null &&
(entry as Record<string, unknown>).playing === true,
);
if (index < 0) return null;
const filename = (playlist[index] as Record<string, unknown>).filename;
return typeof filename === 'string' ? { index, filename } : null;
}
/**
* Swaps mpv's playing playlist entry for `targetUrl` while keeping the rest of the playlist, e.g.
* a queued YouTube watch URL replaced by its resolved direct stream on Windows. Uses only
* long-standing playlist commands (no `loadfile insert-*`, which needs mpv 0.38+).
* Returns false unless the playing entry is confirmed to be `sourceUrl`'s video, so the caller
* falls back to `replace` instead of removing some other queued entry.
*/
async function swapCurrentPlaylistEntry(
deps: YoutubePlaybackLaunchDeps,
targetUrl: string,
sourceUrl: string,
): Promise<boolean> {
if (!deps.requestProperty) return false;
let playlist: unknown;
try {
// One snapshot so the position, count, and entry identity agree with each other.
playlist = await deps.requestProperty('playlist');
} catch {
return false;
}
if (!Array.isArray(playlist)) return false;
const playing = findPlayingPlaylistEntry(playlist);
if (!playing || !targetsSameYoutubeVideo(playing.filename, sourceUrl)) return false;
// The appended entry lands at index `count`; move it right after the playing entry, then remove
// the playing entry so mpv advances onto it.
const count = playlist.length;
deps.sendMpvCommand(['loadfile', targetUrl, 'append']);
deps.sendMpvCommand(['playlist-move', String(count), String(playing.index + 1)]);
deps.sendMpvCommand(['playlist-remove', String(playing.index)]);
return true;
}
function sendPlaybackPrepCommands(sendMpvCommand: (command: Array<string>) => void): void {
sendMpvCommand(['set_property', 'pause', 'yes']);
sendMpvCommand(['set_property', 'sub-auto', 'no']);
@@ -120,7 +171,14 @@ export function createPrepareYoutubePlaybackInMpvHandler(deps: YoutubePlaybackLa
// Keep polling; mpv can report the target path before tracks are ready.
}
} else {
deps.sendMpvCommand(['loadfile', targetUrl, 'replace']);
const sourceUrl = input.sourceUrl?.trim() ?? '';
const swapped =
sourceUrl !== '' &&
targetsSameYoutubeVideo(previousPath, sourceUrl) &&
(await swapCurrentPlaylistEntry(deps, targetUrl, sourceUrl));
if (!swapped) {
deps.sendMpvCommand(['loadfile', targetUrl, 'replace']);
}
}
const deadline = now() + timeoutMs;
@@ -112,8 +112,8 @@ test('youtube playback runtime resolves the socket path lazily for windows start
calls.push(`wait-connected:${timeoutMs}`);
return true;
},
prepareYoutubePlaybackInMpv: async ({ url }) => {
calls.push(`prepare:${url}`);
prepareYoutubePlaybackInMpv: async ({ url, sourceUrl }) => {
calls.push(`prepare:${url}:${sourceUrl}`);
return true;
},
runYoutubePlaybackFlow: async ({ url }) => {
@@ -143,6 +143,51 @@ test('youtube playback runtime resolves the socket path lazily for windows start
});
assert.ok(calls.some((entry) => entry.includes('--input-ipc-server=/tmp/updated.sock')));
// The page URL rides along so prepare can swap a queued entry for the direct stream in place.
assert.ok(calls.includes('prepare:https://example.com/direct:https://youtu.be/demo'));
});
test('youtube playback runtime maps resolved windows streams back to their page urls', async () => {
const streamFor = (url: string) =>
`https://rr1---sn.example.googlevideo.com/videoplayback?src=${encodeURIComponent(url)}`;
const firstUrl = 'https://www.youtube.com/watch?v=abcdefghijk';
const secondUrl = 'https://www.youtube.com/watch?v=bcdefghijkl';
const runtime = createYoutubePlaybackRuntime({
platform: 'win32',
directPlaybackFormat: 'b',
mpvYtdlFormat: 'bestvideo+bestaudio',
autoLaunchTimeoutMs: 2_000,
connectTimeoutMs: 1_000,
getSocketPath: () => '/tmp/mpv.sock',
getMpvConnected: () => true,
invalidatePendingAutoplayReadyFallbacks: () => {},
setAppOwnedFlowInFlight: () => {},
ensureYoutubePlaybackRuntimeReady: async () => {},
resolveYoutubePlaybackUrl: async (url) => streamFor(url),
launchWindowsMpv: async () => ({ ok: false }),
waitForYoutubeMpvConnected: async () => true,
// The second video never loads, so the first stream keeps playing.
prepareYoutubePlaybackInMpv: async ({ url }) => url === streamFor(firstUrl),
runYoutubePlaybackFlow: async () => {},
logInfo: () => {},
logWarn: () => {},
schedule: () => 1 as never,
clearScheduled: () => {},
});
assert.equal(runtime.getYoutubeSourceUrlForStream(streamFor(firstUrl)), null);
await runtime.runYoutubePlaybackFlow({ url: firstUrl, source: 'second-instance' });
await runtime
.runYoutubePlaybackFlow({ url: secondUrl, source: 'second-instance' })
.catch(() => {});
assert.equal(runtime.getYoutubeSourceUrlForStream(streamFor(firstUrl)), firstUrl);
assert.equal(runtime.getYoutubeSourceUrlForStream(streamFor(secondUrl)), secondUrl);
assert.equal(
runtime.getYoutubeSourceUrlForStream('https://rr2---sn.example.googlevideo.com/other'),
null,
);
assert.equal(runtime.getYoutubeSourceUrlForStream('/video/episode.mkv'), null);
});
test('youtube playback runtime starts media cache without blocking the subtitle flow', async () => {
+13 -2
View File
@@ -22,7 +22,7 @@ export type YoutubePlaybackRuntimeDeps = {
resolveYoutubePlaybackUrl: (url: string, format: string) => Promise<string>;
launchWindowsMpv: (playbackUrl: string, args: string[]) => Promise<LaunchResult>;
waitForYoutubeMpvConnected: (timeoutMs: number) => Promise<boolean>;
prepareYoutubePlaybackInMpv: (request: { url: string }) => Promise<boolean>;
prepareYoutubePlaybackInMpv: (request: { url: string; sourceUrl: string }) => Promise<boolean>;
startYoutubeMediaCache?: (url: string) => void | Promise<void>;
runYoutubePlaybackFlow: (request: { url: string }) => Promise<void>;
logInfo: (message: string) => void;
@@ -35,6 +35,10 @@ export function createYoutubePlaybackRuntime(deps: YoutubePlaybackRuntimeDeps) {
let quitOnDisconnectArmed = false;
let quitOnDisconnectArmTimer: ReturnType<typeof setTimeout> | null = null;
let playbackFlowGeneration = 0;
// Windows mpv plays resolved stream URLs, so remember which YouTube page each came from. Kept for
// every resolved stream: a later failed load must not orphan the stream still playing, and mpv
// can return to an earlier swapped-in playlist entry.
const directPlaybackSources = new Map<string, string>();
const clearYoutubePlayQuitOnDisconnectArmTimer = (): void => {
if (quitOnDisconnectArmTimer) {
@@ -65,6 +69,7 @@ export function createYoutubePlaybackRuntime(deps: YoutubePlaybackRuntimeDeps) {
request.url,
deps.directPlaybackFormat,
);
directPlaybackSources.set(playbackUrl, request.url);
deps.logInfo('Resolved direct YouTube playback URL for Windows MPV startup.');
} catch (error) {
deps.logWarn(
@@ -122,7 +127,10 @@ export function createYoutubePlaybackRuntime(deps: YoutubePlaybackRuntimeDeps) {
}, 3000);
}
const mediaReady = await deps.prepareYoutubePlaybackInMpv({ url: playbackUrl });
const mediaReady = await deps.prepareYoutubePlaybackInMpv({
url: playbackUrl,
sourceUrl: request.url,
});
if (!mediaReady) {
throw new Error('Timed out waiting for mpv to load the requested YouTube URL.');
}
@@ -156,5 +164,8 @@ export function createYoutubePlaybackRuntime(deps: YoutubePlaybackRuntimeDeps) {
clearYoutubePlayQuitOnDisconnectArmTimer,
getQuitOnDisconnectArmed: (): boolean => quitOnDisconnectArmed,
runYoutubePlaybackFlow,
/** YouTube page URL for a stream URL this runtime resolved for Windows playback, else null. */
getYoutubeSourceUrlForStream: (mediaPath: string | null | undefined): string | null =>
directPlaybackSources.get(mediaPath?.trim() ?? '') ?? null,
};
}