fix track selection algorithm

AuthorKonata <konata@posteo.jp>
Date
Commitcc6243110cd2e0cf4dc02e34bf91a05d79863ff0
Parenteb1af36
1 file changed, 21 insertions(+), 11 deletions(-)
▾Mserver/src/ffmpeg.ts
@@ -188,21 +188,31 @@ export async function convertWithFFmpeg(
}
}
const seekParams = seekTo === undefined ? [] : ["-ss", secondsToFfmpeg(seekTo)];
const info = await analyzeWithMediainfo(filePath); //analyze video file with mediainfo to get video duration and other metadata
let selectedAudioTrack = 0; //0 as fallback if no language matches and no default is set
const languageArray = languages.split(",").map((s) => s.toLocaleLowerCase());
if (languageArray.length > 0) {
let index = 0;
for (const track of info.media?.track || []) {
if (track["@type"] === "Audio") {
if (track.Default === "Yes") selectedAudioTrack = index; //use the default track if no language matches
if (track.Language && languageArray.includes(track.Language)) {
selectedAudioTrack = index;
//use the first matching track
break;
}
index++;
const tracks = (info.media?.track || []).filter((track) => track["@type"] === "Audio");
let highestPriorityMatch = Number.POSITIVE_INFINITY;
// Check each track for preferred languages in priority order
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
// Store the first default track as fallback
if (track.Default === "Yes" && selectedAudioTrack === 0) {
selectedAudioTrack = i;
}
// Check if this track's language matches any preference
const langIndex = track.Language ? languageArray.indexOf(track.Language.toLocaleLowerCase()) : -1;
// If this is a higher priority match than we've seen before, take it
if (langIndex >= 0 && langIndex < highestPriorityMatch) {
selectedAudioTrack = i;
highestPriorityMatch = langIndex;
// Early exit if we already found the most preferred language (first in array)
if (highestPriorityMatch === 0) break;
}
}
}