diff --git a/docs-site/jellyfin-integration.md b/docs-site/jellyfin-integration.md index 981ffb19..69a37cc3 100644 --- a/docs-site/jellyfin-integration.md +++ b/docs-site/jellyfin-integration.md @@ -31,7 +31,7 @@ Casting finds mpv through `mpv.executablePath`, then `SUBMINER_MPV_PATH`, then ` When you play an episode, by casting or from the terminal, SubMiner adds the episodes around it from the same series to mpv's playlist. Move between them with mpv's playlist keys (`<` and `>` by default) or your playlist UI, and mpv moves on to the next episode when one ends. The series order runs across seasons. Each switch happens in the running mpv and overlay; nothing restarts. -SubMiner waits until the first episode is playing before it looks up the others, so startup is no slower. Every episode you switch to resumes from Jellyfin's saved position and reports progress like one you picked yourself. Its subtitles load the same way. With mpv 0.42 or newer, the playlist lists the queued episodes by title; older mpv versions show their stream URLs. +SubMiner waits until the first episode is playing before it looks up the others, so startup is no slower. Every episode you switch to reports progress like one you picked yourself, and resumes from the position Jellyfin had saved when it was added to the playlist. Its subtitles load the same way. With mpv 0.42 or newer, the playlist lists the queued episodes by title; older mpv versions show their stream URLs. `episodePlaylist.maxEpisodes` caps how many episodes the playlist holds, centered on the playing one. Turn `episodePlaylist.enabled` off to play one episode at a time. Changes apply from the next episode switch. diff --git a/src/main/runtime/jellyfin-episode-playlist.test.ts b/src/main/runtime/jellyfin-episode-playlist.test.ts index f853cee1..f16bbf40 100644 --- a/src/main/runtime/jellyfin-episode-playlist.test.ts +++ b/src/main/runtime/jellyfin-episode-playlist.test.ts @@ -51,6 +51,7 @@ function makeHarness( const playlist: Array<{ filename: string; current: boolean; title?: string }> = []; const commands: Array> = []; let episodeListCalls = 0; + let afterRead: (() => void) | undefined; const queue = createJellyfinEpisodePlaylist({ getSettings: () => settings, listSeriesEpisodeIds: async () => { @@ -58,7 +59,12 @@ function makeHarness( return EPISODES; }, prepareEntry: async (_context, itemId) => entry(itemId), - readMpvPlaylist: async () => playlist.map((item) => ({ ...item })), + readMpvPlaylist: async () => { + const snapshot = playlist.map((item) => ({ ...item })); + // Lets a test move mpv on after the read, like a keypress landing mid-run. + afterRead?.(); + return snapshot; + }, sendMpvCommand: (command) => { commands.push(command); if (command[0] === 'playlist-remove') playlist.splice(Number(command[1]), 1); @@ -84,6 +90,9 @@ function makeHarness( playlist, playing, episodeListCalls: () => episodeListCalls, + setAfterRead: (callback: (() => void) | undefined) => { + afterRead = callback; + }, filenames: () => playlist.map((item) => item.filename), titles: () => playlist.map((item) => item.title), }; @@ -129,6 +138,40 @@ test('queueNeighbors slides the window when mpv moves to a queued episode', asyn assert.equal(harness.episodeListCalls(), 1, 'series order is reused while navigating'); }); +test('queueNeighbors keeps entries still in the window and edits only its far ends', async () => { + const harness = makeHarness(); + harness.playing('e3'); + await harness.queue.queueNeighbors(null, entry('e3')); + harness.playing('e4'); + const commandsBefore = harness.commands.length; + + await harness.queue.queueNeighbors(null, entry('e4')); + + assert.deepEqual( + harness.commands + .slice(commandsBefore) + .filter((command) => command[0] === 'loadfile' || command[0] === 'playlist-remove'), + [ + ['playlist-remove', 0], + ['loadfile', url('e5'), 'insert-at', 2, 'opts-e5'], + ], + ); +}); + +test('queueNeighbors never undoes a navigation that lands after its playlist read', async () => { + const harness = makeHarness(); + harness.playing('e3'); + await harness.queue.queueNeighbors(null, entry('e3')); + harness.playing('e4'); + // The read sees e4 playing; the user steps back to e3 before the edits arrive. + harness.setAfterRead(() => harness.playing('e3')); + + await harness.queue.queueNeighbors(null, entry('e4')); + + assert.equal(harness.playlist.find((item) => item.current)?.filename, url('e3')); + assert.deepEqual(harness.filenames(), [url('e3'), url('e4'), url('e5')]); +}); + test('queueNeighbors leaves the playlist alone once mpv has moved past the item', async () => { const harness = makeHarness(); harness.playing('e3'); diff --git a/src/main/runtime/jellyfin-episode-playlist.ts b/src/main/runtime/jellyfin-episode-playlist.ts index cf0aa167..dffae999 100644 --- a/src/main/runtime/jellyfin-episode-playlist.ts +++ b/src/main/runtime/jellyfin-episode-playlist.ts @@ -87,13 +87,13 @@ export function createJellyfinEpisodePlaylist { - const slots: Array = itemIds.map(() => null); + async function prepareEntries(context: Context, itemIds: string[]): Promise> { + const prepared = new Map(); await Promise.all( - itemIds.map((itemId, index) => + itemIds.map((itemId) => deps.prepareEntry(context, itemId).then( (entry) => { - slots[index] = entry; + prepared.set(itemId, entry); }, (error: unknown) => { deps.logDebug(`Failed to prepare Jellyfin episode ${itemId} for the playlist`, error); @@ -101,22 +101,24 @@ export function createJellyfinEpisodePlaylist entry !== null); + return prepared; } async function queueNeighbors(context: Context, current: Entry): Promise { const run = ++generation; const settings = deps.getSettings(); - let previous: Entry[] = []; - let next: Entry[] = []; + let windowIds = [current.itemId]; if (settings.enabled && current.seriesId) { const episodeIds = await getSeriesEpisodeIds(context, current.seriesId); const window = selectEpisodeWindow(episodeIds, current.itemId, settings.maxEpisodes); - [previous, next] = await Promise.all([ - prepareNeighbors(context, window.previousIds), - prepareNeighbors(context, window.nextIds), - ]); + windowIds = [...window.previousIds, current.itemId, ...window.nextIds]; } + // Entries already queued stay where they are, so only the missing ones are resolved. + const queuedItemIds = new Set([...queued.values()].map(({ entry }) => entry.itemId)); + const prepared = await prepareEntries( + context, + windowIds.filter((itemId) => itemId !== current.itemId && !queuedItemIds.has(itemId)), + ); if (run !== generation) return; const playlist = parseMpvPlaylist(await deps.readMpvPlaylist()); @@ -125,15 +127,28 @@ export function createJellyfinEpisodePlaylist= 0; index -= 1) { - if (index === currentIndex || !queued.has(playlist[index]!.filename)) continue; + // mpv may have moved on since the read, so this only touches entries outside the window + // and never removes one the user could have just navigated to. `model` mirrors mpv's + // playlist by item id (null for entries the app did not queue) as the commands edit it. + const model = playlist.map((item) => + item.filename === current.playbackUrl + ? current.itemId + : (queued.get(item.filename)?.entry.itemId ?? null), + ); + for (let index = model.length - 1; index >= 0; index -= 1) { + const itemId = model[index]; + if (itemId === null || itemId === undefined || windowIds.includes(itemId)) continue; deps.sendMpvCommand(['playlist-remove', index]); - if (index < currentIndex) currentAt -= 1; + model.splice(index, 1); } + const nextQueued = new Map>(); + for (const queuedEpisode of queued.values()) { + if (model.includes(queuedEpisode.entry.itemId)) { + nextQueued.set(queuedEpisode.entry.playbackUrl, queuedEpisode); + } + } + nextQueued.set(current.playbackUrl, { context, entry: current }); // Each insert is followed by its title, sent while the entry is still at that index. const insertEntry = (entry: Entry, index: number) => { deps.sendMpvCommand([ @@ -144,13 +159,30 @@ export function createJellyfinEpisodePlaylist insertEntry(entry, currentAt + 1 + offset)); - // Each insert before the current entry pushes it one slot later. - previous.forEach((entry, offset) => insertEntry(entry, currentAt + offset)); + const currentAt = windowIds.indexOf(current.itemId); + deps.sendMpvCommand([ + 'set_property', + `playlist/${model.indexOf(current.itemId)}/title`, + current.title, + ]); + // Walk outward from the current entry, inserting each missing episode beside its + // neighbor in the window. + let anchor = model.indexOf(current.itemId); + for (const itemId of windowIds.slice(currentAt + 1)) { + const entry = prepared.get(itemId); + if (model.includes(itemId)) anchor = model.indexOf(itemId); + else if (entry) insertEntry(entry, ++anchor); + } + anchor = model.indexOf(current.itemId); + for (const itemId of windowIds.slice(0, currentAt).reverse()) { + const entry = prepared.get(itemId); + if (model.includes(itemId)) anchor = model.indexOf(itemId); + else if (entry) insertEntry(entry, anchor); + } + queued = nextQueued; deps.sendMpvCommand([ 'script-message', MANAGED_PLAYLIST_ENTRIES_SCRIPT_MESSAGE,