Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/v0.1.0-beta4.txt
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ PLAYER
- SponsorBlock now works in the pop-out player and for the next video in the mini player.
- If SponsorBlock can't be reached, the next video plays without skips instead of skipping at the last video's times.
- Rewinding to before a skipped segment skips it again, the same as Flow for Android. To watch it, seek inside the segment.
- A video that falls back to its backup stream now keeps the audio you chose, usually the original, instead of playing an auto-dubbed language. The audio menu works on that stream too.

FIXES
- Scrolling up on the music bar can no longer leave an invisible player covering the app until a reload.
Expand Down
19 changes: 19 additions & 0 deletions src/components/player/Player.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import {
selectPreferredAudioTrackId,
selectPreferredCaptionId,
} from "../../lib/settings/playerRuntime";
import { hlsAudioChoice } from "../../lib/hlsAudioTrack";
import { setSettingValue, useAppSettingsStore } from "../../store/useAppSettingsStore";
import {
clearLiveTiming,
Expand Down Expand Up @@ -554,6 +555,8 @@ export const Player: React.FC<PlayerProps> = ({
|| audioTracks.find((track) => track.isDefault)
|| audioTracks[0]
|| null;
const selectedAudioTrackRef = useRef(selectedAudioTrack);
selectedAudioTrackRef.current = selectedAudioTrack;

const hasSelectedAlternateAudio =
!!selectedAudioTrackId && !!selectedAudioTrack && !selectedAudioTrack.isDefault;
Expand Down Expand Up @@ -1734,7 +1737,10 @@ export const Player: React.FC<PlayerProps> = ({
}
}

// hls.js picks its first track inside its own manifest handling, before any listener here runs.
const audioLanguage = selectedAudioTrackRef.current?.languageCode;
const hls = new Hls({
audioPreference: audioLanguage ? { lang: audioLanguage } : undefined,
enableWorker: true,
lowLatencyMode: false,
maxBufferLength: bufferConfig.maxSeconds,
Expand All @@ -1754,11 +1760,17 @@ export const Player: React.FC<PlayerProps> = ({
hls.on(Hls.Events.MANIFEST_PARSED, () => {
fatalRecoveryAttempts = 0;
logPlayerEventRef.current("hls-manifest-parsed", { levels: hls.levels.length });
const audioChoice = hlsAudioChoice(hls.allAudioTracks, selectedAudioTrackRef.current);
if (audioChoice) hls.setAudioOption(audioChoice);
if (desiredPlayingRef.current) void video.play().catch(() => {});
});
hls.on(Hls.Events.FRAG_LOADED, () => {
fatalRecoveryAttempts = 0;
});
hls.on(Hls.Events.AUDIO_TRACK_SWITCHED, (_event, data) => {
const track = hls.audioTracks[data.id];
logPlayerEventRef.current("hls-audio-track", { name: track?.name, lang: track?.lang, groupId: track?.groupId });
});
hls.on(Hls.Events.LEVEL_UPDATED, (_event, data) => {
if (isLive) stampLiveTiming(video, liveTimingFromPlaylist(hls.targetLatency, data.details.targetduration));
});
Expand Down Expand Up @@ -1818,6 +1830,13 @@ export const Player: React.FC<PlayerProps> = ({
};
}, [bufferConfig, hlsManifestUrl, hlsProxyPrefix, isHlsPlayback, isLive]);

useEffect(() => {
const hls = hlsPlayerRef.current;
if (!hls || hls.allAudioTracks.length === 0) return;
const choice = hlsAudioChoice(hls.allAudioTracks, selectedAudioTrackRef.current);
if (choice) hls.setAudioOption(choice);
}, [selectedAudioTrack?.id]);

useEffect(() => {
if (!isDashPlayback) return;
applyDashQualitySelection();
Expand Down
55 changes: 55 additions & 0 deletions src/lib/hlsAudioTrack.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import { hlsAudioChoice, type HlsAudioOption } from "./hlsAudioTrack";
import type { AudioTrack } from "../types/video";

const option = (name: string, lang: string, contentId?: string): HlsAudioOption => ({
name,
lang,
attrs: contentId ? { "YT-EXT-AUDIO-CONTENT-ID": contentId } : {},
});
const track = (id: string, languageCode: string | null) => ({ id, languageCode }) as AudioTrack;

const arabic = option("العربية - dubbed-auto", "ar", "ar.10");
const german = option("Deutsch (Deutschland) - dubbed-auto", "de-DE", "de-DE.10");
const original = option("American English - original", "en-US", "en-US.4");
const options = [arabic, german, original];

describe("hlsAudioChoice", () => {
it("finds the original by content id, even though a dub comes first", () => {
expect(hlsAudioChoice(options, track("en-US.4-140", "en-US"))).toEqual({
name: "American English - original",
lang: "en-US",
});
});

it("finds a dub the listener chose", () => {
expect(hlsAudioChoice(options, track("de-DE.10-251", "de-DE"))?.name).toBe(german.name);
});

it("tells a dub from an original in the same language by content id", () => {
const dubbedEnglish = option("American English - dubbed-auto", "en-US", "en-US.10");
expect(hlsAudioChoice([dubbedEnglish, original], track("en-US.4-140", "en-US"))?.name).toBe(original.name);
});

it("falls back to the language when the content id isn't listed", () => {
expect(hlsAudioChoice([arabic, option("Deutsch", "de-DE")], track("de-DE.3-140", "de-DE"))?.name).toBe("Deutsch");
});

it("plays the original when the chosen language isn't on offer", () => {
expect(hlsAudioChoice(options, track("fr-FR.10-251", "fr-FR"))?.name).toBe(original.name);
});

it("plays the original when no audio track is known", () => {
expect(hlsAudioChoice(options, null)?.name).toBe(original.name);
});

it("uses the manifest's default when nothing is marked original", () => {
const marked = { ...option("Main", "en"), default: true };
expect(hlsAudioChoice([arabic, marked], null)?.name).toBe("Main");
});

it("leaves it to hls.js when there's nothing to go on", () => {
expect(hlsAudioChoice([{ name: "Default" }], null)).toBeNull();
expect(hlsAudioChoice([], track("en-US.4-140", "en-US"))).toBeNull();
});
});
33 changes: 33 additions & 0 deletions src/lib/hlsAudioTrack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import type { AudioTrack } from "../types/video";

export interface HlsAudioOption {
name: string;
lang?: string;
default?: boolean;
attrs?: Record<string, unknown>;
}

export interface HlsAudioChoice {
name: string;
lang?: string;
}

// Our track ids are YouTube's audio content id plus the itag: "en-US.4-140".
const contentIdOf = (track: AudioTrack) => track.id.replace(/-\d+$/, "");

const hlsContentId = (option: HlsAudioOption) => option.attrs?.["YT-EXT-AUDIO-CONTENT-ID"];

const isOriginal = (option: HlsAudioOption) => /\boriginal\s*$/i.test(option.name);

/**
* The HLS audio track matching the one chosen in the menu. YouTube marks no track as
* default, so hls.js alone plays whichever comes first: usually an auto-dubbed language.
* Name and language identify the track in each audio group, so a quality change keeps it.
*/
export function hlsAudioChoice(options: HlsAudioOption[], selected: AudioTrack | null): HlsAudioChoice | null {
const match = (selected && options.find((option) => hlsContentId(option) === contentIdOf(selected)))
|| (selected?.languageCode && options.find((option) => option.lang === selected.languageCode))
|| options.find(isOriginal)
|| options.find((option) => option.default);
return match ? { name: match.name, lang: match.lang } : null;
}
Loading