refactor mpv state mapping into mpv-state helper

This commit is contained in:
2026-02-14 15:19:37 -08:00
parent 1e20704d39
commit 1fb8e2e168
3 changed files with 66 additions and 15 deletions

View File

@@ -17,6 +17,7 @@ import { requestMpvInitialState, subscribeToMpvProperties } from "./mpv-properti
import {
scheduleMpvReconnect,
} from "./mpv-transport";
import { resolveCurrentAudioStreamIndex } from "./mpv-state";
export {
MPV_REQUEST_ID_SECONDARY_SUB_VISIBILITY,
@@ -338,21 +339,10 @@ export class MpvIpcClient implements MpvClient {
"ff-index"?: number;
}>,
): void {
if (!Array.isArray(tracks)) {
this.currentAudioStreamIndex = null;
return;
}
const audioTracks = tracks.filter((track) => track.type === "audio");
const activeTrack =
audioTracks.find((track) => track.id === this.currentAudioTrackId) ||
audioTracks.find((track) => track.selected === true);
const ffIndex = activeTrack?.["ff-index"];
this.currentAudioStreamIndex =
typeof ffIndex === "number" && Number.isInteger(ffIndex) && ffIndex >= 0
? ffIndex
: null;
this.currentAudioStreamIndex = resolveCurrentAudioStreamIndex(
tracks,
this.currentAudioTrackId,
);
}
send(command: { command: unknown[]; request_id?: number }): boolean {

View File

@@ -0,0 +1,36 @@
import test from "node:test";
import assert from "node:assert/strict";
import { resolveCurrentAudioStreamIndex } from "./mpv-state";
test("resolveCurrentAudioStreamIndex returns selected ff-index when no current track id", () => {
assert.equal(
resolveCurrentAudioStreamIndex(
[
{ type: "audio", id: 1, selected: false, "ff-index": 1 },
{ type: "audio", id: 2, selected: true, "ff-index": 3 },
],
null,
),
3,
);
});
test("resolveCurrentAudioStreamIndex prefers matching current audio track id", () => {
assert.equal(
resolveCurrentAudioStreamIndex(
[
{ type: "audio", id: 1, selected: true, "ff-index": 3 },
{ type: "audio", id: 2, selected: false, "ff-index": 6 },
],
2,
),
6,
);
});
test("resolveCurrentAudioStreamIndex returns null when tracks are not an array", () => {
assert.equal(
resolveCurrentAudioStreamIndex(null, null),
null,
);
});

View File

@@ -0,0 +1,25 @@
export type MpvTrackProperty = {
type?: string;
id?: number;
selected?: boolean;
"ff-index"?: number;
};
export function resolveCurrentAudioStreamIndex(
tracks: Array<MpvTrackProperty> | null | undefined,
currentAudioTrackId: number | null,
): number | null {
if (!Array.isArray(tracks)) {
return null;
}
const audioTracks = tracks.filter((track) => track.type === "audio");
const activeTrack =
audioTracks.find((track) => track.id === currentAudioTrackId) ||
audioTracks.find((track) => track.selected === true);
const ffIndex = activeTrack?.["ff-index"];
return typeof ffIndex === "number" && Number.isInteger(ffIndex) && ffIndex >= 0
? ffIndex
: null;
}