Compare commits

..
4 Commits
Author SHA1 Message Date
github-actions[bot] ddc3a4d77c chore: bump version to 2.12.1 2026-08-04 14:59:38 +00:00
edde746 58d5d3c4ef fix(plex): read external ids from legacy agent and HAMA AniDB guids
Plex only builds the `Guid` array for the Plex Movie / Plex TV Series
agents. A library still on a legacy agent answers with the scalar `guid`
alone, so `fetchExternalIds` returned nothing for it and every consumer
went quiet: trackers logged "no external IDs" and skipped the write,
manual ratings showed "Not available", the detail screen dropped its
watchlist button, and Continue Watching stopped collapsing duplicate
copies. The reverse lookup already read that scalar; only the forward
path ignored it.

Read both shapes from the one request the method already makes, with the
array winning per field and the scalar filling the rest.

HAMA identifies anime by AniDB id and nothing else, which no id set could
carry. AniDB is the Fribb mapping's own primary key, so it now travels on
`ExternalIds` and indexes those rows directly — 7177 of them expose no
tvdb/tmdb/imdb at all and were unreachable by any other path. Only plain
`anidb-` maps: `anidb2`..`anidb9` group several AniDB entries under one
TVDB-numbered show, so the guid names the root entry only.

Two guards keep the new id where it means something. It is trusted for
season 1, because that mode puts the anime there and its specials in
season 0, while a higher season means the library is numbered by TVDB
instead. And it resolves nothing for Trakt and Simkl, which never map
anime and cannot address an AniDB id, so they keep reporting no ids
rather than failing silently further down. `hasCatalogIds` marks the
callers that can only speak IMDb/TMDB/TVDB.

close #1788
2026-08-04 16:56:54 +02:00
edde746 4872adcde3 feat(player): keep the session's explicit track choices across episodes
Episode advance carried live player state, so the viewer's choice only
survived while every episode could serve it: one episode without the
picked audio or subtitle fell back, and the fallback became the carry for
the rest of the session. The screen now keeps the last explicit audio,
subtitle, and secondary-subtitle choices for its lifetime; automatic
outcomes never overwrite them, so the choice retries on every following
episode and reattaches as soon as a catalog can serve it again.

Audio catches up with the subtitle carry from #1785. The old matcher
required raw language equality (a 'sv' pick never found a 'swe' row) and
otherwise took the first same-language track, flipping a commentary or
alternate-mix pick back to the main mix on every episode. Audio now uses
the same evidence bands as subtitles: bridged language parity is
authoritative, a unique title match vouches for untagged tracks, codec
and channel-count parity only break ties, and an ambiguous catalog
declines to the server's own choice instead of guessing. The synthesized
source descriptor also prefers the row's own title over the display title
that collapses to the bare language.

Episode advance previously sent no audio hint to negotiation at all, so a
transcode baked in the server's default audio no matter what was playing.
Both backends now resolve the carried semantics against the new episode's
streams: Jellyfin sends the resolved AudioStreamIndex, Plex feeds the
transcode decision, an explicit per-part stream id always wins, and a
failed match falls back to the server's pick.

close #1785
2026-08-04 16:10:02 +02:00
edde746 61ae314c94 fix(player): tell same-language subtitle rows apart across episodes
The committed track kept the server display title, which collapses to the
bare language ("English") and is identical for every same-language row: a
carried signs/songs choice tied with the full dialogue track on the next
episode and latched onto whichever row sorted first. The row's own title
is preferred now, so the carried intent names the exact row again and the
native pass can match the right container track by title instead of
language order.

Reproduced against a live library where both English ASS rows differ only
by Title ("Styled Subtitles" vs "Signs/OP/ED").

close #1785
2026-08-04 15:22:46 +02:00
31 changed files with 1331 additions and 185 deletions
@@ -160,6 +160,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
committedTrack: committedSubtitleSelection?.primaryTrack,
nativeTrack: currentPlayer.state.track.subtitle,
declinedPreference: committedSubtitleSelection?.declinedPreference,
sessionPreference: _sessionSubtitlePreference,
);
final secondarySubtitlePreference = followServerSelections
? null
@@ -167,6 +168,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
hasCommittedSelection: committedSubtitleSelection != null,
committedTrack: committedSubtitleSelection?.secondaryTrack,
nativeTrack: currentPlayer.state.track.secondarySubtitle,
sessionPreference: _sessionSecondarySubtitlePreference,
);
await _reloadMediaInPlace(
metadata: episodeMetadata,
@@ -178,6 +180,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
// meaningless on the new item, so let preferences pick the track.
useCurrentAudioStreamSelection: false,
preserveCurrentTrackSelection: !followServerSelections,
preservedAudioTrack: _sessionAudioPreference,
preservedSubtitleTrack: primarySubtitlePreference,
preservedSecondarySubtitleTrack: secondarySubtitlePreference,
reason: 'episode navigation',
@@ -222,6 +225,28 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
player == currentPlayer &&
_ownsPlaybackTransition(transitionLease, expected: _PlaybackTransition.switchingSource);
bool sourceSwitchWasSuperseded() => !mounted || player != currentPlayer || transitionLease.wasSuperseded;
void rememberSourceAudioPreference() {
final streamId = newAudioStreamId;
final mediaInfo = _currentMediaInfo;
if (streamId == null || mediaInfo == null) return;
for (final row in mediaInfo.audioTracks) {
if (row.id == streamId) {
_sessionAudioPreference = PlaybackSubtitleResolver.audioTrackForSource(row);
return;
}
}
}
void rememberSourceSubtitlePreference() {
final choice = newSubtitleChoice;
final mediaInfo = _currentMediaInfo;
if (choice == null || mediaInfo == null) return;
// The local-switch path records through the screen's remember chain;
// this covers picks that had to reload, whose resolved outcome never
// reaches _rememberNativeSubtitleSelectionForSlot.
final preference = sessionPreferenceForSourceSubtitleChoice(choice, mediaInfo.subtitleTracks);
if (preference != null) _sessionSubtitlePreference = preference;
}
// Snapshot the backend client before subtitle selection can cross an
// async boundary or the profile-scoped context can disappear.
@@ -276,6 +301,8 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
final isAudioChange = effectiveAudioStreamId != _selectedAudioStreamId;
final isSubtitleChange = newSubtitleChoice != null && newSubtitleChoice != currentSubtitleChoice;
if (!isVersionChange && !isPresetChange && !isAudioChange && !isSubtitleChange) {
rememberSourceAudioPreference();
rememberSourceSubtitlePreference();
return PlaybackSourceChangeOutcome.unchanged;
}
@@ -323,6 +350,10 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
transitionLease: transitionLease,
reason: 'source switch',
);
if (outcome == _MediaReloadOutcome.opened) {
rememberSourceAudioPreference();
rememberSourceSubtitlePreference();
}
return switch (outcome) {
_MediaReloadOutcome.opened => PlaybackSourceChangeOutcome.applied,
_MediaReloadOutcome.rejected => PlaybackSourceChangeOutcome.busy,
@@ -562,6 +593,13 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
final initializationSubtitleTrack = preservesRequestedSubtitleSource
? currentSubtitleTrack
: SubtitlePreference.demoteToIntent(currentSubtitleTrack);
// Same boundary rule for audio: native and Jellyfin stream ids are
// reused per item, so a cross-source carry keeps only its semantics —
// an identity match against a reused id would latch by ordinal and
// bypass the evidence bands' ambiguity decline.
final initializationAudioTrack = preservesRequestedSubtitleSource || currentAudioTrack == null
? currentAudioTrack
: itemAgnosticAudioCarry(currentAudioTrack);
try {
// Eager identity-only: the loading UI shows the new title immediately,
// while the selection/source state flips with the session commit at
@@ -598,6 +636,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
preferredVersionSignature: preferredVersionSignature,
qualityPreset: targetQualityPreset,
selectedAudioStreamId: targetAudioStreamId,
preferredAudioTrack: initializationAudioTrack,
preferredSubtitleTrack: initializationSubtitleTrack,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
@@ -617,7 +656,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
var subtitleSelection = await _resolveSubtitleSelectionForOpen(
metadata: metadata,
result: result,
preferredAudioTrack: currentAudioTrack,
preferredAudioTrack: initializationAudioTrack,
preferredSubtitleTrack: currentSubtitleTrack,
preferredSecondarySubtitleTrack: currentSecondarySubtitleTrack,
preserveSubtitleSourceIdentity:
@@ -771,7 +810,7 @@ extension _VideoPlayerEpisodeNavigationMethods on VideoPlayerScreenState {
metadata: metadata,
plexClient: plexClient,
getProfileSettings: () => userProfileProvider.profileSettings,
preferredAudioTrack: currentAudioTrack,
preferredAudioTrack: initializationAudioTrack,
// A declined carry stays alive for the native passes: freezing the
// resolver's off verdict here would turn a metadata mismatch into a
// navigation-priority off that no late track can undo (#1785).
@@ -123,6 +123,7 @@ extension _VideoPlayerPlaybackStartMethods on VideoPlayerScreenState {
selectedMediaSourceId: _requestedMediaSourceId,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
preferredAudioTrack: _preferredAudioTrack,
preferredSubtitleTrack: _preferredSubtitleTrack,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
+67 -4
View File
@@ -153,6 +153,10 @@ bool playerChromeStartsVisible({required bool isTv}) => !isTv;
/// boundary; native state is a fallback for sessions created before
/// source-backed selection was recorded.
///
/// [sessionPreference] is the screen's last explicit viewer choice and wins
/// outright: automatic outcomes never overwrite it, so a catalog-gap episode
/// cannot reset the choice for the rest of the session.
///
/// [declinedPreference] is the committed selection's unserved carry: its off
/// is fallout from a metadata mismatch, not a viewer choice, so it must not
/// harden into an explicit off on the next item (#1785).
@@ -161,7 +165,10 @@ SubtitlePreference? subtitlePreferenceForItemChange({
required SubtitleTrack? committedTrack,
required SubtitleTrack? nativeTrack,
SubtitlePreference? declinedPreference,
SubtitlePreference? sessionPreference,
}) {
final sessionIntent = SubtitlePreference.demoteToIntent(sessionPreference);
if (sessionIntent != null) return sessionIntent;
SubtitlePreference? normalize(SubtitleTrack? track, {required bool preserveOff}) {
if (track == null) return null;
if (track.id == SubtitleTrack.off.id) return preserveOff ? const SubtitlePreference.off() : null;
@@ -223,6 +230,26 @@ PlaybackSubtitleSelection subtitleSelectionForUserPick({
);
}
/// Session-preference form of a source-catalog subtitle choice that had to
/// go through a reload instead of a local track switch.
///
/// The authoritative row — not the reload's outcome — becomes the session
/// preference: a failed resolution must not turn the viewer's pick into a
/// carried off. Returns null when the row is absent from [rows] so a stale
/// id never overwrites the existing session preference.
SubtitlePreference? sessionPreferenceForSourceSubtitleChoice(
PlaybackSourceSubtitleChoice choice,
List<MediaSubtitleTrack> rows,
) {
if (choice.isOff) return const SubtitlePreference.off();
for (final row in rows) {
if (row.id == choice.sourceStreamId) {
return SubtitlePreference.track(PlaybackSubtitleResolver.subtitleTrackForSource(row));
}
}
return null;
}
/// The in-place media-source transitions a [VideoPlayerScreenState] can run.
/// They are mutually exclusive by construction — entry points bail while a
/// transition is in flight.
@@ -425,6 +452,14 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
AudioTrack? _preferredAudioTrack;
SubtitlePreference? _preferredSubtitleTrack;
SubtitlePreference? _preferredSecondarySubtitleTrack;
/// Last explicit track choices made on this screen. They survive in-place
/// reloads but not route replacement. Automatic selections never overwrite
/// them, so an episode with a catalog gap cannot reset the viewer's choice
/// for the rest of the session (#1785).
AudioTrack? _sessionAudioPreference;
SubtitlePreference? _sessionSubtitlePreference;
SubtitlePreference? _sessionSecondarySubtitlePreference;
bool _serverSupportsTranscoding = false;
// Kicked off early in the player initialization attempt for online non-live playback so
// the metadata fetch (and transcode-decision HTTP, if non-original preset)
@@ -1148,6 +1183,7 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
preferredVersionSignature: widget.preferredVersionSignature,
qualityPreset: _selectedQualityPreset,
selectedAudioStreamId: _selectedAudioStreamId,
preferredAudioTrack: _preferredAudioTrack,
preferredSubtitleTrack: _preferredSubtitleTrack,
sessionIdentifier: _playbackSessionIdentifier,
transcodeSessionId: _playbackTranscodeSessionId,
@@ -1894,7 +1930,12 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
}
}
Future<void> _onAudioTrackChanged(AudioTrack track) async => _trackManager?.onAudioTrackSelectedByUser(track);
Future<void> _onAudioTrackChanged(AudioTrack track) async {
if (track.id != AudioTrack.auto.id && track.id != AudioTrack.off.id) {
_sessionAudioPreference = track;
}
await _trackManager?.onAudioTrackSelectedByUser(track);
}
Future<void> _onSubtitleTrackChanged(SubtitleTrack track, {int? sourceStreamId}) async {
_rememberNativeSubtitleSelection(track, sourceStreamId: sourceStreamId);
@@ -1919,10 +1960,16 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
required _SubtitleSelectionSlot slot,
int? sourceStreamId,
}) {
final session = _playbackSession;
if (session == null) return;
final currentSelection = session.subtitleSelection;
if (track.id == SubtitleTrack.off.id) {
switch (slot) {
case _SubtitleSelectionSlot.primary:
_sessionSubtitlePreference = const SubtitlePreference.off();
case _SubtitleSelectionSlot.secondary:
_sessionSecondarySubtitlePreference = const SubtitlePreference.off();
}
final session = _playbackSession;
if (session == null) return;
final currentSelection = session.subtitleSelection;
_updatePlaybackSessionSubtitleSelection(session, switch (slot) {
_SubtitleSelectionSlot.primary => const PlaybackSubtitleSelection.off(),
// Dropping only the secondary must not relabel the primary's
@@ -1938,6 +1985,10 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
return;
}
final session = _playbackSession;
if (session == null) return;
final currentSelection = session.subtitleSelection;
final info = _currentMediaInfo;
final currentPlayer = player;
@@ -1989,6 +2040,18 @@ class VideoPlayerScreenState extends State<VideoPlayerScreen> with WidgetsBindin
sourceTrack: sourceTrack,
sidecar: sidecar,
);
final resolvedTrack = switch (slot) {
_SubtitleSelectionSlot.primary => selection.primaryTrack,
_SubtitleSelectionSlot.secondary => selection.secondaryTrack,
};
if (resolvedTrack != null) {
switch (slot) {
case _SubtitleSelectionSlot.primary:
_sessionSubtitlePreference = SubtitlePreference.track(resolvedTrack);
case _SubtitleSelectionSlot.secondary:
_sessionSecondarySubtitlePreference = SubtitlePreference.track(resolvedTrack);
}
}
_updatePlaybackSessionSubtitleSelection(session, selection);
if (mounted) _setPlayerState(() {});
}
@@ -364,7 +364,12 @@ class AnilistCatalogSource with CatalogWatchlistMachinery implements CatalogSour
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async {
if (!external.hasAny) return null;
final rows = await _fribb.lookup(tvdbId: external.tvdb, tmdbId: external.tmdb, imdbId: external.imdb);
final rows = await _fribb.lookup(
anidbId: external.anidb,
tvdbId: external.tvdb,
tmdbId: external.tmdb,
imdbId: external.imdb,
);
final row = _pickRow(kind, rows);
if (row?.anilistId == null) return null;
return CatalogItemIds(
+6 -1
View File
@@ -368,7 +368,12 @@ class MalCatalogSource with CatalogWatchlistMachinery implements CatalogSource {
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async {
if (!external.hasAny) return null;
final rows = await _fribb.lookup(tvdbId: external.tvdb, tmdbId: external.tmdb, imdbId: external.imdb);
final rows = await _fribb.lookup(
anidbId: external.anidb,
tvdbId: external.tvdb,
tmdbId: external.tmdb,
imdbId: external.imdb,
);
final malId = _pickRow(kind, rows)?.malId;
if (malId == null) return null;
return CatalogItemIds(mal: malId, imdb: external.imdb, tmdb: external.tmdb, tvdb: external.tvdb);
@@ -103,7 +103,9 @@ class PlexCatalogSource with CatalogWatchlistMachinery implements CatalogSource,
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async {
if (!external.hasAny) return null;
// Plex Discover matches on imdb/tmdb/tvdb only; an AniDB-only item has
// nothing to send it.
if (!external.hasCatalogIds) return null;
final metadata = await _client.match(external);
final matchedKind = metadata == null ? null : _kindFor(metadata['type']);
if (metadata == null || matchedKind != kind) return null;
@@ -565,7 +565,7 @@ class SimklCatalogSource with CatalogWatchlistMachinery implements CatalogSource
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async =>
external.hasAny ? CatalogItemIds.fromExternal(external) : null;
external.hasCatalogIds ? CatalogItemIds.fromExternal(external) : null;
@override
Future<WatchlistKeyPage> fetchWatchlistKeyPage(int page, int limit) async {
@@ -117,7 +117,7 @@ class TraktCatalogSource with CatalogWatchlistMachinery implements CatalogSource
@override
Future<CatalogItemIds?> resolveItemIds(MediaKind kind, ExternalIds external) async =>
external.hasAny ? CatalogItemIds.fromExternal(external) : null;
external.hasCatalogIds ? CatalogItemIds.fromExternal(external) : null;
@override
Future<CatalogDetail> fetchDetail(CatalogItem item, {int castLimit = 20, int relatedLimit = 20}) async {
@@ -406,6 +406,8 @@ class DataAggregationService {
if (tmdb != null) keys.add('$scope:tmdb:$tmdb');
final tvdb = externalIds.tvdb;
if (tvdb != null) keys.add('$scope:tvdb:$tvdb');
final anidb = externalIds.anidb;
if (anidb != null) keys.add('$scope:anidb:$anidb');
}
String? _stableMediaGuid(String? guid) {
@@ -176,7 +176,11 @@ mixin _JellyfinPlaybackMethods on _JellyfinClientInternals {
final preset = options.qualityPreset;
final audioPreset = options.audioQualityPreset ?? AudioQualityPreset.original;
final wantsOriginal = isTrack ? audioPreset.isOriginal : preset.isOriginal;
final requestedAudioStreamId = _validJellyfinAudioStreamId(options.selectedAudioStreamId, mediaInfo);
final requestedAudioStreamId = options.selectedAudioStreamId == null
? options.preferredAudioTrack == null
? null
: findSourceAudioTrackForIntent(options.preferredAudioTrack!, mediaInfo.audioTracks)?.id
: _validJellyfinAudioStreamId(options.selectedAudioStreamId, mediaInfo);
final requestedSubtitleStreamId = _validJellyfinSubtitleStreamId(options.preferredSubtitleTrack, mediaInfo);
final int? maxStreamingBitrate = wantsOriginal
? null
@@ -42,6 +42,13 @@ class PlaybackInitializationOptions {
/// server pick".
final int? selectedAudioStreamId;
/// Semantic audio carry for negotiation when [selectedAudioStreamId] is
/// null: the id belongs to another item, but language, title, codec, and
/// channels let a backend resolve the equivalent stream on this one
/// (transcodes bake the audio choice in, so post-open switching cannot
/// recover it). Resolution failure falls back to the server's pick.
final AudioTrack? preferredAudioTrack;
/// Preferred subtitle carried across navigation/reloads. Backends that put
/// embedded subtitles in the rendition can use this during negotiation;
/// sidecar-capable backends keep subtitle delivery independent.
@@ -62,6 +69,7 @@ class PlaybackInitializationOptions {
this.qualityPreset = TranscodeQualityPreset.original,
this.audioQualityPreset,
this.selectedAudioStreamId,
this.preferredAudioTrack,
this.preferredSubtitleTrack,
this.sessionIdentifier,
this.transcodeSessionId,
+21 -12
View File
@@ -263,7 +263,11 @@ class PlaybackSubtitleResolver {
final playable = sidecar?.track;
return SubtitleTrack(
id: 'source:${sourceTrack.id}',
title: playable?.title ?? sourceTrack.displayTitle ?? sourceTrack.title ?? sourceTrack.language,
// The row's own title first: server display titles collapse to the bare
// language ("English") and are identical across same-language rows, so
// a carried intent built from them cannot tell a Signs/Songs track from
// the full dialogue track on the next episode (#1785).
title: sourceTrack.title ?? playable?.title ?? sourceTrack.displayTitle ?? sourceTrack.language,
language: playable?.language ?? sourceTrack.languageCode ?? sourceTrack.language,
codec: playable?.codec ?? sourceTrack.codec,
isDefault: sourceTrack.selected,
@@ -325,18 +329,23 @@ class PlaybackSubtitleResolver {
return choices[(normalizedCurrentIndex + advances) % choices.length];
}
/// Stable semantic descriptor for a source audio row — the audio twin of
/// [subtitleTrackForSource]. The row's own title comes first: server
/// display titles collapse to the bare language and cannot tell a
/// commentary or alternate mix from the main track on another item.
static AudioTrack audioTrackForSource(MediaAudioTrack track) {
return AudioTrack(
id: 'source:${track.id}',
title: track.title ?? track.displayTitle ?? track.language,
language: track.languageCode ?? track.language,
codec: track.codec,
channels: track.channels,
isDefault: track.selected,
);
}
static List<AudioTrack> _audioTracksForSource(MediaSourceInfo? mediaInfo) {
return [
for (final track in mediaInfo?.audioTracks ?? const <MediaAudioTrack>[])
AudioTrack(
id: 'source:${track.id}',
title: track.displayTitle ?? track.title ?? track.language,
language: track.languageCode ?? track.language,
codec: track.codec,
channels: track.channels,
isDefault: track.selected,
),
];
return [for (final track in mediaInfo?.audioTracks ?? const <MediaAudioTrack>[]) audioTrackForSource(track)];
}
}
+36 -30
View File
@@ -73,6 +73,7 @@ import 'plex_lyrics_parser.dart';
import 'plex_mappers.dart';
import 'plex_playback_mapper.dart';
import 'playback_initialization_types.dart';
import 'track_selection_service.dart';
part 'plex_client/parts/live_tv.dart';
part 'plex_client/parts/playlists.dart';
@@ -1929,30 +1930,6 @@ class PlexClient
return _getFirstMetadataJsonFromData(data);
}
/// Fetch the raw `Guid` array for a metadata item (`includeGuids=1`).
///
/// Returns the list of `{id: 'imdb://tt...'}` maps as Plex returns them, or
/// an empty list if the item has no external IDs / can't be fetched.
/// Used by the Trakt integration to match Plex items against Trakt's catalog.
Future<List<dynamic>> fetchExternalGuids(String ratingKey) async {
try {
final response = await _getWithFailover('/library/metadata/$ratingKey', queryParameters: {'includeGuids': 1});
final data = response.data;
if (data is! Map) return const [];
final container = data['MediaContainer'] as Map?;
final metadata = container?['Metadata'];
if (metadata is! List || metadata.isEmpty) return const [];
final first = metadata.first;
if (first is! Map) return const [];
final guids = first['Guid'];
if (guids is List) return guids;
return const [];
} catch (e) {
appLogger.d('fetchExternalGuids failed for $ratingKey', error: e);
return const [];
}
}
/// Mark media as watched (transport only — see [MediaServerClient.markWatched]).
Future<void> markAsWatched(String ratingKey) async {
await _getWithFailover(
@@ -3252,6 +3229,10 @@ class PlexClient
if (!data.hasValidVideoUrl) {
throw PlaybackException(t.messages.fileInfoNotAvailable, reason: PlaybackFailureReason.noPlayableSource);
}
final carriedAudioTrack = options.selectedAudioStreamId == null ? options.preferredAudioTrack : null;
final carriedAudioStreamId = carriedAudioTrack == null || data.mediaInfo == null
? null
: findSourceAudioTrackForIntent(carriedAudioTrack, data.mediaInfo!.audioTracks)?.id;
// Tracks consult the music preset — [qualityPreset] is video-shaped
// (resolution/videoQuality) and is ignored for audio.
@@ -3286,7 +3267,9 @@ class PlexClient
return _transcodeFallbackResult(data, result.outcome, options);
}
final resolvedAudioId = _resolveAudioStreamId(options.selectedAudioStreamId, data.mediaInfo);
final resolvedAudioId = carriedAudioTrack == null
? _resolveAudioStreamId(options.selectedAudioStreamId, data.mediaInfo)
: carriedAudioStreamId;
final result = await buildTranscodeStartPath(
ratingKey: options.metadata.id,
mediaIndex: data.selectedMediaIndex,
@@ -3314,7 +3297,7 @@ class PlexClient
);
}
return _transcodeFallbackResult(data, result.outcome, options);
return _transcodeFallbackResult(data, result.outcome, options, activeAudioStreamId: carriedAudioStreamId);
}
return PlaybackInitializationResult(
@@ -3323,6 +3306,7 @@ class PlexClient
mediaInfo: data.mediaInfo,
subtitleSidecars: _buildExternalSubtitles(data.mediaInfo),
isOffline: false,
activeAudioStreamId: carriedAudioStreamId,
playMethod: 'DirectPlay',
playSessionId: options.sessionIdentifier,
selectedMediaIndex: data.selectedMediaIndex,
@@ -3340,8 +3324,9 @@ class PlexClient
PlaybackInitializationResult _transcodeFallbackResult(
PlexVideoPlaybackData data,
TranscodeDecisionOutcome outcome,
PlaybackInitializationOptions options,
) {
PlaybackInitializationOptions options, {
int? activeAudioStreamId,
}) {
final fallbackReason = outcome == TranscodeDecisionOutcome.directPlayOnly
? TranscodeFallbackReason.directPlayOnly
: TranscodeFallbackReason.decisionFailed;
@@ -3354,6 +3339,7 @@ class PlexClient
isOffline: false,
isTranscoding: false,
fallbackReason: fallbackReason,
activeAudioStreamId: activeAudioStreamId,
playMethod: 'DirectPlay',
playSessionId: options.sessionIdentifier,
selectedMediaIndex: data.selectedMediaIndex,
@@ -3861,10 +3847,30 @@ class PlexClient
@override
Map<String, String> get streamHeaders => Map.unmodifiable(config.headers);
/// Reads both guid shapes Plex can answer with. The `Guid` array only exists
/// for items matched by the Plex Movie / Plex TV Series agents; a library
/// still on a legacy agent (HAMA, `com.plexapp.agents.thetvdb`, ...) carries
/// its ids in the scalar `guid` instead, so reading only the array left every
/// tracker, watchlist and dedupe path blind to those libraries (#1788).
///
/// The array wins per field; the scalar only fills what it left null.
@override
Future<ExternalIds> fetchExternalIds(String itemId) async {
final guids = await fetchExternalGuids(itemId);
return ExternalIds.fromGuids(guids);
try {
final response = await _getWithFailover('/library/metadata/$itemId', queryParameters: {'includeGuids': 1});
final data = response.data;
if (data is! Map) return const ExternalIds();
final metadata = (data['MediaContainer'] as Map?)?['Metadata'];
if (metadata is! List || metadata.isEmpty) return const ExternalIds();
final first = metadata.first;
if (first is! Map) return const ExternalIds();
final guids = first['Guid'];
final modern = guids is List ? ExternalIds.fromGuids(guids) : const ExternalIds();
return modern.fillFrom(ExternalIds.fromLegacyPlexGuid(first['guid']));
} catch (e) {
appLogger.d('fetchExternalIds failed for $itemId', error: e);
return const ExternalIds();
}
}
/// Map id-verified candidates to items, dropping any sequel the server does
+113 -46
View File
@@ -357,93 +357,147 @@ MediaSubtitleTrack? findPlexTrackForMpvSubtitle(
/// signal is a title like "Swedish" are common, and declining them turned the
/// viewer's subtitles off on every episode advance. Codec/external parity is
/// never sufficient evidence on its own (an arbitrary untagged row would
/// reintroduce the #1716 wrong-track class); it only breaks ties WITHIN the
/// title-matched set, and a residual tie declines rather than guesses.
/// reintroduce the #1716 wrong-track class); technical parity only breaks
/// ties the stronger tiers left, and any tie still standing at the top
/// declines rather than guesses — in every band, so two indistinguishable
/// same-language rows never latch by catalog order.
MediaSubtitleTrack? findSourceTrackForIntent(SubtitleIntent intent, List<MediaSubtitleTrack> sourceTracks) {
return _findTrackForIntent(
intent,
return _findTrackByEvidenceBands(
sourceTracks,
intentLanguage: intent.language,
isSelectable: (_) => true,
classMatches: (row) => row.effectiveForced == intent.forced,
language: (row) => row.languageCode ?? row.language,
effectiveForced: (row) => row.effectiveForced,
titleScore: (row) => _titleScore(intent.title, row.title, row.displayTitle),
codec: (row) => row.codec,
isExternal: (row) => row.isExternal,
codecMatches: (row) => _subtitleCodecsMatch(intent.codec, row.codec),
extraScore: (row) => intent.isExternal == row.isExternal ? 1 : 0,
);
}
/// Native-track twin of [findSourceTrackForIntent], for catalogs the source
/// side cannot describe (legacy offline sidecars) and late-arriving tracks.
SubtitleTrack? findNativeTrackForIntent(SubtitleIntent intent, List<SubtitleTrack> tracks) {
return _findTrackForIntent(
intent,
return _findTrackByEvidenceBands(
tracks,
intentLanguage: intent.language,
isSelectable: (track) => track.id != SubtitleTrack.auto.id && track.id != SubtitleTrack.off.id,
classMatches: (track) => track.effectiveForced == intent.forced,
language: (track) => track.language,
effectiveForced: (track) => track.effectiveForced,
titleScore: (track) => _titleScore(intent.title, track.title, null),
codec: (track) => track.codec,
isExternal: (track) => track.isExternal,
codecMatches: (track) => _subtitleCodecsMatch(intent.codec, track.codec),
extraScore: (track) => intent.isExternal == track.isExternal ? 1 : 0,
);
}
/// Shared scorer behind [findSourceTrackForIntent]/[findNativeTrackForIntent].
/// Audio twin of [findSourceTrackForIntent]: the source-catalog row that
/// serves a cross-item audio carry. [carried] is a semantic vehicle — its id
/// belongs to another item; language, title, codec, and channels are the
/// signal. Audio has no forced-class gate; channel-count parity replaces the
/// external-parity tiebreaker.
MediaAudioTrack? findSourceAudioTrackForIntent(AudioTrack carried, List<MediaAudioTrack> rows) {
return _findTrackByEvidenceBands(
rows,
intentLanguage: carried.language,
isSelectable: (_) => true,
classMatches: (_) => true,
language: (row) => row.languageCode ?? row.language,
titleScore: (row) => _titleScore(carried.title, row.title, row.displayTitle),
codecMatches: (row) => _audioCodecsMatch(carried.codec, row.codec),
extraScore: (row) => carried.channels != null && carried.channels == row.channels ? 1 : 0,
);
}
/// Native twin of [findSourceAudioTrackForIntent].
AudioTrack? findNativeAudioTrackForIntent(AudioTrack carried, List<AudioTrack> tracks) {
return _findTrackByEvidenceBands(
tracks,
intentLanguage: carried.language,
isSelectable: (track) => track.id != AudioTrack.auto.id && track.id != AudioTrack.off.id,
classMatches: (_) => true,
language: (track) => track.language,
titleScore: (track) => _titleScore(carried.title, track.title, null),
codecMatches: (track) => _audioCodecsMatch(carried.codec, track.codec),
extraScore: (track) => carried.channels != null && carried.channels == track.channels ? 1 : 0,
);
}
/// Sentinel id for a cross-item audio carry. Native player ids ('1', '2', …)
/// and Jellyfin `source:<Index>` ids are reused per item, so a carried track
/// with its original id can identity-match a DIFFERENT track that happens to
/// sit at the same position on the next episode — bypassing the evidence
/// bands and their ambiguity decline.
const String carriedAudioTrackId = 'carried';
/// Strips item-bound identity from an audio carry so only its semantics may
/// speak — the audio twin of [SubtitlePreference.demoteToIntent]. Same-item
/// reloads keep the original track and its identity fast path.
AudioTrack itemAgnosticAudioCarry(AudioTrack track) => track.copyWith(id: carriedAudioTrackId);
/// Shared evidence matcher behind the cross-item intent matchers.
///
/// Score bands keep the evidence classes strictly ordered: a language-parity
/// match starts at 10 while a title-evidence match tops out at 9
/// (codec 5 + title 3 + external 1), so the two can never tie and language
/// always outranks a title coincidence.
T? _findTrackForIntent<T extends Object>(
SubtitleIntent intent,
/// Candidates are compared lexicographically, strongest evidence first:
/// declared-language parity, then the semantic title/role match, then
/// technical parity (codec, then channels/external). Each tier only breaks
/// ties left by the tiers above it — a codec that changed between episodes
/// can never outvote the title that names the viewer's track, and language
/// parity always outranks a title coincidence. A tie left standing at the
/// top means the catalog cannot say which row the viewer meant: the match
/// declines and the ladder falls to the server's own per-item choice.
T? _findTrackByEvidenceBands<T extends Object>(
List<T> candidates, {
required String? intentLanguage,
required bool Function(T) isSelectable,
required bool Function(T) classMatches,
required String? Function(T) language,
required bool Function(T) effectiveForced,
required int Function(T) titleScore,
required String? Function(T) codec,
required bool Function(T) isExternal,
required bool Function(T) codecMatches,
required int Function(T) extraScore,
}) {
T? bestMatch;
var bestScore = -1;
var bestIsTitleEvidence = false;
List<int>? bestKey;
var bestIsAmbiguous = false;
for (final candidate in candidates) {
if (!isSelectable(candidate)) continue;
if (effectiveForced(candidate) != intent.forced) continue;
if (!classMatches(candidate)) continue;
final candidateLanguage = language(candidate);
final candidateTitleScore = titleScore(candidate);
final hasLanguageParity = intent.language != null && candidateLanguage != null;
var score = 0;
final hasLanguageParity = intentLanguage != null && candidateLanguage != null;
if (hasLanguageParity) {
// A declared language on both sides stays authoritative: a
// contradiction declines no matter what the title says.
if (!_languagesMatch(intent.language, candidateLanguage)) continue;
score += 10;
if (!_languagesMatch(intentLanguage, candidateLanguage)) continue;
} else if (candidateTitleScore < 3) {
// Language evidence is missing on at least one side; only a real
// title match may serve the intent then.
continue;
}
if (_subtitleCodecsMatch(intent.codec, codec(candidate))) score += 5;
score += candidateTitleScore;
if (intent.isExternal == isExternal(candidate)) score += 1;
if (score > bestScore) {
bestScore = score;
final key = [
hasLanguageParity ? 1 : 0,
candidateTitleScore,
codecMatches(candidate) ? 1 : 0,
extraScore(candidate),
];
final comparison = bestKey == null ? 1 : _compareEvidenceKeys(key, bestKey);
if (comparison > 0) {
bestKey = key;
bestMatch = candidate;
bestIsTitleEvidence = !hasLanguageParity;
bestIsAmbiguous = false;
} else if (score == bestScore && bestIsTitleEvidence) {
// Only title-evidence matches can tie (their band never reaches a
// language-parity score). Two rows the tiebreakers cannot separate
// mean the catalog cannot say which one the viewer meant.
} else if (comparison == 0) {
bestIsAmbiguous = true;
}
}
if (bestIsTitleEvidence && bestIsAmbiguous) return null;
if (bestIsAmbiguous) return null;
return bestMatch;
}
int _compareEvidenceKeys(List<int> a, List<int> b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return a[i].compareTo(b[i]);
}
return 0;
}
/// Find the MPV audio track that matches a Plex audio track
AudioTrack? findMpvTrackForPlexAudio(
MediaAudioTrack plexTrack,
@@ -716,10 +770,6 @@ class TrackSelectionService {
return null;
}
AudioTrack? findBestAudioMatch(List<AudioTrack> availableTracks, AudioTrack preferred) {
return findBestTrackMatch<AudioTrack>(availableTracks, preferred, (t) => t.id, (t) => t.title, (t) => t.language);
}
AudioTrack? findAudioTrackByProfile(List<AudioTrack> availableTracks, MediaServerUserProfile profile) {
if (availableTracks.isEmpty || !profile.autoSelectAudio) return null;
@@ -947,12 +997,29 @@ class TrackSelectionService {
AudioTrack? trackToSelect;
// Priority 1: Try to match preferred track from navigation
// Priority 1: the carried preference. Full identity first (a same-item
// reload passing back the identical track), then the cross-item evidence
// bands — bridged language parity or a unique title match with
// codec/channel tiebreaks. This replaces the old first-match language
// tier, which latched onto an arbitrary same-language (or same-untagged)
// row and lost the viewer's commentary/dub distinction across episodes.
if (preferredAudioTrack != null) {
trackToSelect = findBestAudioMatch(availableTracks, preferredAudioTrack);
trackToSelect =
availableTracks
.where(
(track) =>
track.id != AudioTrack.auto.id &&
track.id != AudioTrack.off.id &&
track.id == preferredAudioTrack.id &&
track.title == preferredAudioTrack.title &&
track.language == preferredAudioTrack.language,
)
.firstOrNull ??
findNativeAudioTrackForIntent(preferredAudioTrack, availableTracks);
if (trackToSelect != null) {
return TrackSelectionResult(trackToSelect, TrackSelectionPriority.navigation);
}
appLogger.d('Audio carry declined: ${preferredAudioTrack.language}/${preferredAudioTrack.title}');
}
// Priority 2: Check server-selected track from media info
+30 -7
View File
@@ -21,17 +21,29 @@ class FribbIndex implements RemoteIndex {
/// MAL entry can be matched back to library external ids.
final Map<int, FribbMappingRow> byMal;
const FribbIndex({required this.byTvdb, required this.byTmdb, required this.byImdb, this.byMal = const {}});
/// AniDB id → its (single) row. AniDB is the dataset's own primary key, so
/// unlike the three catalog indexes this one never resolves to a list.
/// Plex's HAMA agent identifies anime by AniDB id and nothing else, which is
/// the only way a library item reaches the mapping through it (#1788).
final Map<int, FribbMappingRow> byAnidb;
const FribbIndex({
required this.byTvdb,
required this.byTmdb,
required this.byImdb,
this.byMal = const {},
this.byAnidb = const {},
});
@override
bool get isEmpty => byTvdb.isEmpty && byTmdb.isEmpty && byImdb.isEmpty && byMal.isEmpty;
bool get isEmpty => byTvdb.isEmpty && byTmdb.isEmpty && byImdb.isEmpty && byMal.isEmpty && byAnidb.isEmpty;
@override
String get logSummary => '${byTvdb.length} tvdb entries';
}
abstract interface class FribbMappingLookup {
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId});
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId});
Future<FribbMappingRow?> lookupByMal(int malId);
}
@@ -56,11 +68,19 @@ class FribbMappingStore extends EtagCachedRemoteStore<FribbIndex> implements Fri
static final FribbMappingStore instance = FribbMappingStore._();
/// Look up rows by Plex external IDs. Returns the first non-empty candidate
/// list in preference order: tvdb → tmdb → imdb.
/// Look up rows by a library item's external IDs. Returns the first non-empty
/// candidate list in preference order: anidb → tvdb → tmdb → imdb.
///
/// AniDB leads because it is the dataset's primary key: it names exactly one
/// entry, where a tvdb/tmdb/imdb hit can be a whole split-cour show the
/// caller still has to disambiguate.
@override
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId}) async {
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId}) async {
final idx = await ensureLoaded();
if (anidbId != null) {
final hit = idx.byAnidb[anidbId];
if (hit != null) return [hit];
}
if (tvdbId != null) {
final hits = idx.byTvdb[tvdbId];
if (hits != null && hits.isNotEmpty) return hits;
@@ -102,6 +122,7 @@ FribbIndex parseFribbIndex(String raw) {
final byTmdb = <int, List<FribbMappingRow>>{};
final byImdb = <String, List<FribbMappingRow>>{};
final byMal = <int, FribbMappingRow>{};
final byAnidb = <int, FribbMappingRow>{};
var skipped = 0;
for (final raw in decoded) {
@@ -126,8 +147,10 @@ FribbIndex parseFribbIndex(String raw) {
}
final mal = row.malId;
if (mal != null) byMal.putIfAbsent(mal, () => row);
final anidb = row.anidbId;
if (anidb != null) byAnidb.putIfAbsent(anidb, () => row);
}
if (skipped > 0) appLogger.w('Fribb: skipped $skipped malformed row(s)');
return FribbIndex(byTvdb: byTvdb, byTmdb: byTmdb, byImdb: byImdb, byMal: byMal);
return FribbIndex(byTvdb: byTvdb, byTmdb: byTmdb, byImdb: byImdb, byMal: byMal, byAnidb: byAnidb);
}
+43 -4
View File
@@ -65,6 +65,12 @@ class TrackerRatingContext {
/// show-level external IDs. Anime-Lists XML is used when available to
/// disambiguate same-season split-cour episode ranges by AniDB id.
///
/// A HAMA-matched Plex library supplies an AniDB id and nothing else. That is
/// Fribb's own primary key, so it resolves an anime directly — but Anime-Lists
/// maps tvdb/tmdb episode coordinates onto AniDB rather than the reverse, so
/// those items get no episode mapping and fall back to the show's own
/// numbering, which is what HAMA's plain `anidb` mode already uses.
///
/// The Fribb lookup is skipped when [needsFribb] returns false — set this way
/// for Trakt (which never uses anime IDs) and for a Simkl-only configuration,
/// so those users don't pay the 5.6 MB mapping download they'll never need.
@@ -203,8 +209,14 @@ class TrackerIdResolver {
required bool isMovie,
}) async {
if (!external.hasAny) return null;
if (!_needsFribb()) return TrackerIds(external: external, anime: null);
final rows = await _store.lookup(tvdbId: external.tvdb, tmdbId: external.tmdb, imdbId: external.imdb);
if (!_needsFribb()) return _withoutAnimeMapping(external);
final anidbId = _usableAnidbId(external, season: isMovie ? null : isEpisodeSeason);
final rows = await _store.lookup(
anidbId: anidbId,
tvdbId: external.tvdb,
tmdbId: external.tmdb,
imdbId: external.imdb,
);
final animeMatch = isMovie || isEpisodeSeason == null || episodeNumber == null
? null
: await _lookupAnimeEpisodeMatchByCoordinate(external, isEpisodeSeason, episodeNumber);
@@ -225,10 +237,37 @@ class TrackerIdResolver {
);
}
/// The id set with no Fribb mapping attached, for trackers that never use one.
///
/// Null for an AniDB-only item: Trakt and Simkl are the only trackers that
/// report `needsFribb == false`, and neither speaks AniDB, so handing them a
/// context they cannot address would trade the "no external IDs" log for a
/// silent no-op further down.
TrackerIds? _withoutAnimeMapping(ExternalIds external) =>
external.hasCatalogIds ? TrackerIds(external: external, anime: null) : null;
/// The AniDB id to look Fribb up by, or null when it cannot be trusted.
///
/// Only Plex's HAMA agent supplies one, and only in its plain `anidb` mode:
/// one AniDB entry per Plex show, its episodes in season 1 and its specials
/// in season 0. A higher season means the library is numbered by TVDB
/// instead — HAMA warns about that itself — so the guid's entry does not
/// describe what is playing and the tvdb/tmdb/imdb ladder must handle it.
int? _usableAnidbId(ExternalIds external, {required int? season}) {
final anidb = external.anidb;
if (anidb == null) return null;
return season == null || season == 1 ? anidb : null;
}
Future<TrackerIds?> _buildShowRating(ExternalIds external, {int? season}) async {
if (!external.hasAny) return null;
if (!_needsFribb()) return TrackerIds(external: external, anime: null);
final rows = await _store.lookup(tvdbId: external.tvdb, tmdbId: external.tmdb, imdbId: external.imdb);
if (!_needsFribb()) return _withoutAnimeMapping(external);
final rows = await _store.lookup(
anidbId: _usableAnidbId(external, season: season),
tvdbId: external.tvdb,
tmdbId: external.tmdb,
imdbId: external.imdb,
);
FribbMappingRow? row;
final animeIds = season == null
+41 -9
View File
@@ -44,12 +44,14 @@ class ExternalSeasonRef {
int get hashCode => Object.hash(tvdb, tmdb);
}
/// External IDs (IMDb / TMDB / TVDB) extracted from a media server's
/// External IDs (IMDb / TMDB / TVDB / AniDB) extracted from a media server's
/// metadata. Shared by the Trakt and tracker resolvers.
///
/// - **Plex** stores modern IDs in a `Guid` array (`imdb://tt123`,
/// `tmdb://456`, `tvdb://789`) and some legacy agents expose one scalar
/// `guid`. Use [ExternalIds.fromGuids] or [ExternalIds.fromLegacyPlexGuid].
/// `tmdb://456`, `tvdb://789`) and legacy agents expose one scalar `guid`
/// instead — the `Guid` array only exists for the Plex Movie / Plex TV
/// Series agents. Use [ExternalIds.fromGuids] and [fillFrom] with
/// [ExternalIds.fromLegacyPlexGuid] so both shapes are read.
/// - **Jellyfin** stores them inline as a `ProviderIds` map on every
/// `BaseItemDto`. Use [ExternalIds.fromJellyfinProviderIds].
class ExternalIds {
@@ -57,9 +59,20 @@ class ExternalIds {
final int? tmdb;
final int? tvdb;
const ExternalIds({this.imdb, this.tmdb, this.tvdb});
/// AniDB series id, only ever produced by Plex's HAMA agent. Separate from
/// the three catalog ids because almost nothing accepts it: it names a Fribb
/// row (and through it MAL/AniList/Simkl) but Trakt, Plex Discover, Seerr and
/// the Anime-Lists episode mappings are all keyed the other way.
final int? anidb;
bool get hasAny => imdb != null || tmdb != null || tvdb != null;
const ExternalIds({this.imdb, this.tmdb, this.tvdb, this.anidb});
bool get hasAny => hasCatalogIds || anidb != null;
/// The ids a title database can be queried with. Callers that can only search
/// IMDb/TMDB/TVDB gate on this rather than [hasAny], so an AniDB-only item
/// does not send them looking for something they cannot express.
bool get hasCatalogIds => imdb != null || tmdb != null || tvdb != null;
/// True when any id form matches [other]. Used to verify reverse-lookup
/// candidates (never yields false positives; the two sides may carry
@@ -67,7 +80,19 @@ class ExternalIds {
bool intersects(ExternalIds other) =>
(imdb != null && imdb == other.imdb) ||
(tmdb != null && tmdb == other.tmdb) ||
(tvdb != null && tvdb == other.tvdb);
(tvdb != null && tvdb == other.tvdb) ||
(anidb != null && anidb == other.anidb);
/// This set with every absent id taken from [other].
///
/// Used to read a Plex item that carries both shapes: the modern `Guid` array
/// wins per field and the legacy scalar `guid` only fills what it left null.
ExternalIds fillFrom(ExternalIds other) => ExternalIds(
imdb: imdb ?? other.imdb,
tmdb: tmdb ?? other.tmdb,
tvdb: tvdb ?? other.tvdb,
anidb: anidb ?? other.anidb,
);
/// Round-trips through the persisted tracker write queue. Absent ids stay
/// absent so a re-read yields the same [hasAny]/[intersects] answers.
@@ -75,12 +100,14 @@ class ExternalIds {
if (imdb != null) 'imdb': imdb,
if (tmdb != null) 'tmdb': tmdb,
if (tvdb != null) 'tvdb': tvdb,
if (anidb != null) 'anidb': anidb,
};
factory ExternalIds.fromJson(Map<String, Object?> json) => ExternalIds(
imdb: json['imdb'] as String?,
tmdb: (json['tmdb'] as num?)?.toInt(),
tvdb: (json['tvdb'] as num?)?.toInt(),
anidb: (json['anidb'] as num?)?.toInt(),
);
factory ExternalIds.fromGuids(List<dynamic> guids) {
@@ -104,9 +131,11 @@ class ExternalIds {
/// Build from a legacy Plex item's scalar `guid`.
///
/// Only agent formats that map directly to IMDb, TMDB, or TVDB are
/// recognized. HAMA AniDB identifiers require an external mapping and are
/// deliberately left unsupported here.
/// HAMA composes its guid as `<source>-<id>` over
/// `anidb|anidb2..9|tvdb|tvdb2..9|tmdb|tsdb|imdb`. Only plain `anidb-` is
/// mapped: `anidb2`..`anidb9` are HAMA's grouping modes, where several AniDB
/// entries share one Plex show under TVDB-shaped seasons, so the guid names
/// the root entry only and would mislabel every later season.
factory ExternalIds.fromLegacyPlexGuid(Object? guid) {
if (guid is! String || guid.isEmpty) return const ExternalIds();
@@ -129,6 +158,9 @@ class ExternalIds {
if (source == 'imdb') {
return ExternalIds(imdb: _normalizeImdb(id, allowBareDigits: true));
}
if (source == 'anidb') {
return ExternalIds(anidb: _parseNumericId(id));
}
if (source == 'tmdb' || source == 'tsdb') {
return ExternalIds(tmdb: _parseNumericId(id));
}
+1 -1
View File
@@ -1,7 +1,7 @@
name: plezy
description: "A beautiful Plex and Jellyfin client for Flutter"
publish_to: "none"
version: 2.12.0+126
version: 2.12.1+127
environment:
sdk: ">=3.12.0 <4.0.0"
@@ -60,6 +60,7 @@ void main() {
hasCommittedSelection: true,
committedTrack: committed,
nativeTrack: SubtitleTrack.off,
sessionPreference: null,
);
expect(result, isA<SubtitleIntentPreference>());
@@ -71,6 +72,45 @@ void main() {
expect(intent.isExternal, isTrue);
});
test('session subtitle intent wins over the committed outcome at an item boundary', () {
const sessionPreference = SubtitlePreference.intent(
SubtitleIntent(language: 'swe', forced: false, title: 'Swedish', codec: 'srt'),
);
final result = subtitlePreferenceForItemChange(
hasCommittedSelection: true,
committedTrack: const SubtitleTrack(id: 'source:4', language: 'eng', title: 'English', codec: 'srt'),
nativeTrack: const SubtitleTrack(id: '2', language: 'eng', title: 'English', codec: 'srt'),
sessionPreference: sessionPreference,
);
expect(result, sessionPreference);
});
test('session subtitle off stays off at an item boundary', () {
expect(
subtitlePreferenceForItemChange(
hasCommittedSelection: true,
committedTrack: const SubtitleTrack(id: 'source:4', language: 'eng'),
nativeTrack: const SubtitleTrack(id: '2', language: 'eng'),
sessionPreference: const SubtitlePreference.off(),
),
const SubtitlePreference.off(),
);
});
test('semantics-free session subtitle preference falls back to the committed flow', () {
final result = subtitlePreferenceForItemChange(
hasCommittedSelection: true,
committedTrack: const SubtitleTrack(id: 'source:4', language: 'eng', title: 'English', codec: 'srt'),
nativeTrack: SubtitleTrack.off,
sessionPreference: const SubtitlePreference.track(SubtitleTrack(id: 'source:9')),
);
expect(result, isA<SubtitleIntentPreference>());
expect((result! as SubtitleIntentPreference).intent.language, 'eng');
});
test('item-change subtitle preference derives forced-ness from a forced title (#1716)', () {
const committed = SubtitleTrack(id: 'source:4', title: 'FR Forced [ASS]', language: 'fra', codec: 'ass');
@@ -233,6 +273,55 @@ void main() {
expect(selection.secondarySourceStreamId, isNull);
});
test('a reload-path source subtitle pick becomes the session preference (#1785)', () {
// Picks that cannot switch locally go through a full reload and never
// reach the native remember chain; the authoritative source row still
// has to become the session preference — including its discriminating
// title — or a later fallback episode erases the choice.
final rows = [
MediaSubtitleTrack(
id: 3,
languageCode: 'eng',
title: 'Full Subtitles',
displayTitle: 'English',
codec: 'ass',
selected: true,
forced: false,
),
MediaSubtitleTrack(
id: 4,
languageCode: 'eng',
title: 'Signs & Songs',
displayTitle: 'English',
codec: 'ass',
selected: false,
forced: false,
),
];
final captured = sessionPreferenceForSourceSubtitleChoice(const PlaybackSourceSubtitleChoice.source(4), rows);
expect(captured, isA<SubtitleTrackPreference>());
expect((captured! as SubtitleTrackPreference).track.title, 'Signs & Songs');
// The captured preference crosses the next episode boundary as its
// intent, keeping the signs/dialogue distinction.
final carried = SubtitlePreference.demoteToIntent(captured);
expect(carried, isA<SubtitleIntentPreference>());
expect((carried! as SubtitleIntentPreference).intent.title, 'Signs & Songs');
expect((carried as SubtitleIntentPreference).intent.language, 'eng');
});
test('a reload-path off choice and a stale row id capture correctly', () {
expect(
sessionPreferenceForSourceSubtitleChoice(const PlaybackSourceSubtitleChoice.off(), const []),
const SubtitlePreference.off(),
);
// A row the catalog no longer carries must not overwrite the session
// preference with a fabricated pick.
final rows = [MediaSubtitleTrack(id: 3, languageCode: 'eng', codec: 'ass', selected: false, forced: false)];
expect(sessionPreferenceForSourceSubtitleChoice(const PlaybackSourceSubtitleChoice.source(99), rows), isNull);
});
test('a secondary-only change keeps the primary declined carry alive (#1785)', () {
const declined = SubtitlePreference.intent(
SubtitleIntent(language: 'swe', forced: false, title: 'Swedish', codec: 'srt'),
@@ -37,9 +37,10 @@ class _FakeFribb implements FribbMappingLookup {
_FakeFribb(this.rows);
@override
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId}) async => [
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId}) async => [
for (final row in rows)
if ((tvdbId != null && row.tvdbId == tvdbId) ||
if ((anidbId != null && row.anidbId == anidbId) ||
(tvdbId != null && row.tvdbId == tvdbId) ||
(tmdbId != null && (row.tmdbIds?.contains(tmdbId) ?? false)) ||
(imdbId != null && (row.imdbIds?.contains(imdbId) ?? false)))
row,
@@ -32,9 +32,10 @@ class _FakeFribb implements FribbMappingLookup {
_FakeFribb(this.rows);
@override
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId}) async => [
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId}) async => [
for (final row in rows)
if ((tvdbId != null && row.tvdbId == tvdbId) ||
if ((anidbId != null && row.anidbId == anidbId) ||
(tvdbId != null && row.tvdbId == tvdbId) ||
(tmdbId != null && (row.tmdbIds?.contains(tmdbId) ?? false)) ||
(imdbId != null && (row.imdbIds?.contains(imdbId) ?? false)))
row,
@@ -64,6 +64,56 @@ JellyfinClient _clientWithPlaybackInfo(
);
}
Future<({PlaybackInitializationResult result, Uri playbackInfoUri, Map<String, dynamic> playbackInfoBody})>
_initializeJellyfinAudioCarry({int? selectedAudioStreamId, AudioTrack? preferredAudioTrack}) async {
late Uri playbackInfoUri;
late String playbackInfoBody;
final client = _clientWithPlaybackInfo(
(request) async {
playbackInfoUri = request.url;
playbackInfoBody = request.body;
return jsonResponse({
'MediaSources': [
{'Id': 'src-1'},
],
});
},
itemSources: [
{
'Id': 'src-1',
'Container': 'mkv',
'MediaStreams': [
{'Index': 0, 'Type': 'Video'},
{'Index': 1, 'Type': 'Audio', 'Codec': 'aac', 'Language': 'eng', 'IsDefault': true},
{'Index': 4, 'Type': 'Audio', 'Codec': 'flac', 'Language': 'jpn', 'Title': 'Main'},
],
},
],
);
try {
final result = await client.getPlaybackInitialization(
PlaybackInitializationOptions(
metadata: testMediaItem(
id: 'item-1',
backend: MediaBackend.jellyfin,
kind: MediaKind.episode,
serverId: 'srv-1',
),
selectedMediaIndex: 0,
selectedAudioStreamId: selectedAudioStreamId,
preferredAudioTrack: preferredAudioTrack,
),
);
return (
result: result,
playbackInfoUri: playbackInfoUri,
playbackInfoBody: jsonDecode(playbackInfoBody) as Map<String, dynamic>,
);
} finally {
client.close();
}
}
/// Serves [routes] as JSON keyed by request path and records the last URL seen
/// for each path; every other path answers 404.
({JellyfinClient client, Map<String, Uri> requests}) _routedClient(Map<String, Object> routes) {
@@ -1342,6 +1392,38 @@ void main() {
expect(uri.queryParameters['Container'], 'mkv');
});
test('semantic carried audio resolves against the selected source before PlaybackInfo negotiation', () async {
final initialized = await _initializeJellyfinAudioCarry(
preferredAudioTrack: const AudioTrack(id: 'source:99', language: 'jpn', title: 'Main', codec: 'flac'),
);
expect(initialized.playbackInfoUri.queryParameters['AudioStreamIndex'], '4');
expect(initialized.playbackInfoBody['AudioStreamIndex'], 4);
expect(initialized.result.activeAudioStreamId, 4);
expect(initialized.result.mediaInfo!.audioTracks.singleWhere((track) => track.id == 4).selected, isTrue);
});
test('explicit Jellyfin audio stream wins over a conflicting semantic carry', () async {
final initialized = await _initializeJellyfinAudioCarry(
selectedAudioStreamId: 1,
preferredAudioTrack: const AudioTrack(id: 'source:99', language: 'jpn', title: 'Main', codec: 'flac'),
);
expect(initialized.playbackInfoUri.queryParameters['AudioStreamIndex'], '1');
expect(initialized.playbackInfoBody['AudioStreamIndex'], 1);
expect(initialized.result.activeAudioStreamId, 1);
});
test('unresolvable semantic audio carry lets Jellyfin choose the stream', () async {
final initialized = await _initializeJellyfinAudioCarry(
preferredAudioTrack: const AudioTrack(id: 'source:99', language: 'swe'),
);
expect(initialized.playbackInfoUri.queryParameters.containsKey('AudioStreamIndex'), isFalse);
expect(initialized.playbackInfoBody.containsKey('AudioStreamIndex'), isFalse);
expect(initialized.result.activeAudioStreamId, isNull);
});
test('stale selected audio stream is not sent for a source without that stream', () async {
Uri? playbackInfoUri;
String? playbackInfoBody;
@@ -605,6 +605,110 @@ void main() {
expect(result.isOff, isTrue);
expect(result.declinedPreference, isNull);
});
test('same-language rows are told apart by their titles across episodes (#1785)', () {
// Real-world shape (Madoka Magica on Plex): both rows English ASS with
// the bare displayTitle "English"; only Title separates the full
// dialogue track from the signs/songs track.
MediaSubtitleTrack row(int id, String title, {bool selected = false}) => MediaSubtitleTrack(
id: id,
language: 'English',
languageCode: 'eng',
title: title,
displayTitle: 'English',
codec: 'ass',
selected: selected,
forced: false,
);
// E1: the viewer picks the signs track and the session commits it. The
// committed track must keep the discriminating row title, not the
// language-only display title.
final committed = PlaybackSubtitleResolver.subtitleTrackForSource(row(53164, 'Signs/OP/ED'));
expect(committed.title, 'Signs/OP/ED');
// Episode boundary demotes the committed reference to its intent.
final carried = SubtitlePreference.demoteToIntent(SubtitlePreference.track(committed));
// E2: same pair; the dialogue row sorts first AND is server-selected —
// the carried signs choice must still win over both.
final result = PlaybackSubtitleResolver.resolve(
metadata: metadata,
mediaInfo: _mediaInfo([row(53193, 'Styled Subtitles', selected: true), row(53194, 'Signs/OP/ED')]),
sidecars: const [],
preferredSubtitleTrack: carried,
preserveSourceIdentity: false,
);
expect(result.primarySourceStreamId, 53194);
expect(result.declinedPreference, isNull);
});
test('a Jellyfin signs pick beats the server per-episode default on the next episode (#1785)', () {
// Verbatim shape from a live Jellyfin server (Attack on Titan): both
// rows English ASS, discriminated by Title, and the server names the
// full-dialogue row (DefaultSubtitleStreamIndex 3) on every episode.
MediaSourceInfo episodeInfo() => jellyfinMediaSourceToMediaSourceInfo({
'Id': 'src-1',
'DefaultSubtitleStreamIndex': 3,
'MediaStreams': [
{'Index': 1, 'Type': 'Audio', 'Language': 'jpn', 'IsDefault': true},
{
'Index': 3,
'Type': 'Subtitle',
'Language': 'eng',
'Codec': 'ass',
'Title': 'Full Subtitles',
'DisplayTitle': 'Full Subtitles - English - Default - ASS',
'IsDefault': true,
},
{
'Index': 4,
'Type': 'Subtitle',
'Language': 'eng',
'Codec': 'ass',
'Title': 'Signs & Songs',
'DisplayTitle': 'Signs & Songs - English - ASS',
},
],
});
final e1 = episodeInfo();
final picked = e1.subtitleTracks.firstWhere((row) => row.id == 4);
final committed = PlaybackSubtitleResolver.subtitleTrackForSource(picked);
expect(committed.title, 'Signs & Songs');
final carried = SubtitlePreference.demoteToIntent(SubtitlePreference.track(committed));
final result = PlaybackSubtitleResolver.resolve(
metadata: metadata,
mediaInfo: episodeInfo(),
sidecars: const [],
preferredSubtitleTrack: carried,
preserveSourceIdentity: false,
);
expect(result.primarySourceStreamId, 4);
expect(result.declinedPreference, isNull);
});
});
test('audio source descriptor keeps the discriminating row title', () {
// Server display titles collapse to the bare language; a commentary or
// alternate mix is only identifiable by the row's own title.
final row = MediaAudioTrack(
id: 7,
languageCode: 'eng',
title: 'Commentary',
displayTitle: 'English',
codec: 'ac3',
channels: 6,
selected: false,
);
final track = PlaybackSubtitleResolver.audioTrackForSource(row);
expect(track.id, 'source:7');
expect(track.title, 'Commentary');
expect(track.language, 'eng');
expect(track.channels, 6);
});
test('selected embedded subtitle keeps sidecars out of the open', () {
@@ -0,0 +1,113 @@
import 'dart:convert';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:plezy/database/app_database.dart';
import 'package:plezy/services/plex_api_cache.dart';
import '../test_helpers/backend_client_fixtures.dart';
http.Response _json(Object body) => http.Response(jsonEncode(body), 200, headers: {'content-type': 'application/json'});
/// A `/library/metadata/{id}` response carrying whichever guid shapes the
/// server's agent produces.
http.Response _metadata({List<Object>? guidArray, Object? scalarGuid}) => _json({
'MediaContainer': {
'Metadata': [
{'ratingKey': 'show-1', 'type': 'show', 'title': 'Show', 'guid': ?scalarGuid, 'Guid': ?guidArray},
],
},
});
void main() {
late AppDatabase db;
setUp(() {
db = AppDatabase.forTesting(NativeDatabase.memory());
PlexApiCache.initialize(db);
});
tearDown(() async {
await db.close();
});
test('reads the modern Guid array and asks for it', () async {
late Uri requestUri;
final client = testPlexClient(
handler: (request) async {
requestUri = request.url;
return _metadata(
guidArray: [
{'id': 'imdb://tt12345'},
{'id': 'tmdb://456'},
{'id': 'tvdb://789'},
],
scalarGuid: 'plex://show/abc',
);
},
);
addTearDown(client.close);
final ids = await client.fetchExternalIds('show-1');
expect(requestUri.path, '/library/metadata/show-1');
expect(requestUri.queryParameters['includeGuids'], '1');
expect((ids.imdb, ids.tmdb, ids.tvdb), ('tt12345', 456, 789));
});
// Plex only builds the `Guid` array for the Plex Movie / Plex TV Series
// agents. A library still on a legacy agent answers with the scalar `guid`
// alone, and reading only the array left every tracker blind to it (#1788).
test('falls back to a legacy agent scalar guid', () async {
final client = testPlexClient(
handler: (request) async => _metadata(scalarGuid: 'com.plexapp.agents.thetvdb://315500?lang=en'),
);
addTearDown(client.close);
final ids = await client.fetchExternalIds('show-1');
expect(ids.tvdb, 315500);
});
test('maps a HAMA AniDB guid, which carries no catalog id at all', () async {
final client = testPlexClient(
handler: (request) async => _metadata(scalarGuid: 'com.plexapp.agents.hama://anidb-11905?lang=en'),
);
addTearDown(client.close);
final ids = await client.fetchExternalIds('show-1');
expect(ids.anidb, 11905);
expect(ids.hasAny, isTrue);
expect(ids.hasCatalogIds, isFalse);
});
test('the Guid array wins per field and the scalar fills the rest', () async {
final client = testPlexClient(
handler: (request) async => _metadata(
guidArray: [
{'id': 'tvdb://789'},
],
scalarGuid: 'com.plexapp.agents.hama://tvdb-315500',
),
);
addTearDown(client.close);
final ids = await client.fetchExternalIds('show-1');
expect(ids.tvdb, 789);
});
test('an unmatched item and a failed request both resolve to no ids', () async {
final unmatched = testPlexClient(
handler: (request) async => _metadata(scalarGuid: 'com.plexapp.agents.none://315500'),
);
addTearDown(unmatched.close);
expect((await unmatched.fetchExternalIds('show-1')).hasAny, isFalse);
final failing = testPlexClient(handler: (request) async => http.Response('nope', 500));
addTearDown(failing.close);
expect((await failing.fetchExternalIds('show-1')).hasAny, isFalse);
});
}
@@ -10,6 +10,7 @@ import 'package:plezy/media/media_backend.dart';
import 'package:plezy/media/media_kind.dart';
import 'package:plezy/media/media_source_info.dart';
import 'package:plezy/mpv/mpv.dart';
import 'package:plezy/models/transcode_quality_preset.dart';
import 'package:plezy/services/playback_initialization_types.dart';
import 'package:plezy/services/plex_api_cache.dart';
@@ -34,6 +35,91 @@ void main() {
PlexClient makeClient(Future<http.Response> Function(http.Request request) handler) =>
testPlexClient(serverId: ServerId('server-id'), handler: handler);
Future<({PlaybackInitializationResult result, Uri decisionUri})> initializeTranscodeAudio({
int? selectedAudioStreamId,
AudioTrack? preferredAudioTrack,
}) async {
late Uri decisionUri;
final client = makeClient((request) async {
if (request.url.path == '/library/metadata/42') {
return http.Response(
jsonEncode({
'MediaContainer': {
'Metadata': [
{
'ratingKey': '42',
'type': 'episode',
'title': 'Episode',
'Media': [
{
'id': 7,
'container': 'mkv',
'Part': [
{
'id': 99,
'key': '/library/parts/99/file.mkv',
'Stream': [
{'streamType': 1, 'id': 300, 'codec': 'h264'},
{
'streamType': 2,
'id': 301,
'index': 0,
'codec': 'aac',
'languageCode': 'eng',
'title': 'Original',
'selected': true,
},
{
'streamType': 2,
'id': 305,
'index': 1,
'codec': 'flac',
'languageCode': 'jpn',
'title': 'Main',
},
],
},
],
},
],
},
],
},
}),
200,
headers: {'content-type': 'application/json'},
);
}
if (request.url.path == '/video/:/transcode/universal/decision') {
decisionUri = request.url;
return http.Response(
jsonEncode({
'MediaContainer': {'generalDecisionCode': 1001, 'transcodeDecisionCode': 1001},
}),
200,
headers: {'content-type': 'application/json'},
);
}
return http.Response('unexpected request', 500);
});
try {
final result = await client.getPlaybackInitialization(
PlaybackInitializationOptions(
metadata: testMediaItem(id: '42', backend: MediaBackend.plex, kind: MediaKind.episode, serverId: 'server-id'),
selectedMediaIndex: 0,
selectedAudioStreamId: selectedAudioStreamId,
preferredAudioTrack: preferredAudioTrack,
qualityPreset: TranscodeQualityPreset.p720_3mbps,
sessionIdentifier: 'session-id',
transcodeSessionId: 'transcode-id',
),
);
return (result: result, decisionUri: decisionUri);
} finally {
client.close();
}
}
MediaSourceInfo mediaInfoWithSubtitles(List<MediaSubtitleTrack> subtitleTracks) {
return MediaSourceInfo(
videoUrl: 'https://plex.example.com/video.mkv',
@@ -68,6 +154,34 @@ void main() {
expect(requests.single.url.queryParameters['allParts'], '1');
});
test('semantic carried audio is sent to the Plex transcode decision', () async {
final initialized = await initializeTranscodeAudio(
preferredAudioTrack: const AudioTrack(id: 'source:999', language: 'jpn', title: 'Main', codec: 'flac'),
);
expect(initialized.decisionUri.queryParameters['audioStreamID'], '305');
expect(initialized.result.activeAudioStreamId, 305);
});
test('explicit Plex audio stream wins over a conflicting semantic carry', () async {
final initialized = await initializeTranscodeAudio(
selectedAudioStreamId: 301,
preferredAudioTrack: const AudioTrack(id: 'source:999', language: 'jpn', title: 'Main', codec: 'flac'),
);
expect(initialized.decisionUri.queryParameters['audioStreamID'], '301');
expect(initialized.result.activeAudioStreamId, 301);
});
test('unresolvable semantic audio carry lets the Plex transcoder choose the stream', () async {
final initialized = await initializeTranscodeAudio(
preferredAudioTrack: const AudioTrack(id: 'source:999', language: 'swe'),
);
expect(initialized.decisionUri.queryParameters.containsKey('audioStreamID'), isFalse);
expect(initialized.result.activeAudioStreamId, isNull);
});
test('playback metadata request includes streams for transcode sidecar subtitles', () async {
final requests = <Uri>[];
final client = makeClient((request) async {
+152 -44
View File
@@ -16,7 +16,7 @@ import '../test_helpers/media_items.dart';
// integration point (`selectAndApplyTracks`). We cover:
//
// - `languageMatches` — direct, base-code, and ISO 639 variation matching.
// - `findBestTrackMatch` / `findBestAudioMatch` / `findBestSubtitleMatch` —
// - `findBestTrackMatch` / `findBestSubtitleMatch` —
// id+title+language exact, title+language, language-only, and the
// "auto"/"no" filtering rule.
// - `findAudioTrackByProfile` — picks the first preferred-language match,
@@ -232,49 +232,6 @@ void main() {
// findBestTrackMatch (via the audio/subtitle wrappers)
// ============================================================
group('findBestAudioMatch', () {
final svc = _svc();
test('exact id + title + language match wins', () {
final tracks = [_audio('1', lang: 'eng', title: 'Stereo'), _audio('2', lang: 'eng', title: 'Surround')];
final preferred = _audio('2', lang: 'eng', title: 'Surround');
expect(svc.findBestAudioMatch(tracks, preferred), tracks[1]);
});
test('falls back to title + language when id differs', () {
final tracks = [_audio('1', lang: 'eng', title: 'Stereo'), _audio('2', lang: 'eng', title: 'Surround')];
// Different id but matching title+language → tracks[1].
final preferred = _audio('999', lang: 'eng', title: 'Surround');
expect(svc.findBestAudioMatch(tracks, preferred), tracks[1]);
});
test('falls back to language-only match', () {
final tracks = [_audio('1', lang: 'eng', title: 'Stereo')];
final preferred = _audio('999', lang: 'eng', title: 'Different');
expect(svc.findBestAudioMatch(tracks, preferred), tracks[0]);
});
test('returns null when no language match exists', () {
final tracks = [_audio('1', lang: 'fre')];
final preferred = _audio('1', lang: 'eng');
expect(svc.findBestAudioMatch(tracks, preferred), isNull);
});
test('filters out auto and no tracks before matching', () {
final tracks = [AudioTrack.auto, AudioTrack.off, _audio('3', lang: 'eng')];
final preferred = _audio('3', lang: 'eng');
expect(svc.findBestAudioMatch(tracks, preferred), tracks[2]);
});
test('returns null on an empty list', () {
expect(svc.findBestAudioMatch(const [], _audio('1', lang: 'eng')), isNull);
});
test('returns null when only auto/no tracks remain after filtering', () {
expect(svc.findBestAudioMatch([AudioTrack.auto, AudioTrack.off], _audio('1', lang: 'eng')), isNull);
});
});
group('findBestSubtitleMatch', () {
final svc = _svc();
@@ -352,6 +309,64 @@ void main() {
expect(result.track, tracks[1]);
});
test('Priority 1: a cross-item semantic carry matches through the evidence bands', () {
// The carried track's id belongs to the previous episode; language and
// title must still find the equivalent native track here.
final tracks = [_audio('1', lang: 'eng', title: 'Main'), _audio('2', lang: 'eng', title: 'Commentary')];
final carried = _audio('source:99', lang: 'eng', title: 'Commentary');
final result = _svc().selectAudioTrack(tracks, carried);
expect(result!.priority, TrackSelectionPriority.navigation);
expect(result.track, tracks[1]);
});
test('Priority 1: a declined audio carry falls to the server-selected track', () {
final tracks = [_audio('A', lang: 'eng'), _audio('B', lang: 'fre')];
final info = _info(
audio: [
_plexAudio(1, language: 'eng', languageCode: 'eng', selected: true),
_plexAudio(2, language: 'fre', languageCode: 'fre'),
],
);
// Swedish is gone on this episode: the carry declines instead of
// latching onto an arbitrary row, and the server's pick plays.
final result = _svc(info: info).selectAudioTrack(tracks, _audio('source:9', lang: 'swe'));
expect(result!.priority, TrackSelectionPriority.serverSelected);
expect(result.track.language, 'eng');
});
test('a demoted cross-item carry cannot latch a reused native id', () {
// Native ids are per-item ordinals: the previous episode's id '2' names
// a DIFFERENT track here. The boundary demotes the carry to semantics
// only; an indistinguishable same-language pair then declines to the
// server's choice instead of silently keeping the old ordinal.
final tracks = [
_audio('1', lang: 'eng', codec: 'aac', channels: 2),
_audio('2', lang: 'eng', codec: 'aac', channels: 2),
];
final info = _info(
audio: [
_plexAudio(1, language: 'eng', languageCode: 'eng', selected: true),
_plexAudio(2, language: 'eng', languageCode: 'eng'),
],
);
final carriedRaw = _audio('2', lang: 'eng', codec: 'aac', channels: 2);
final carried = itemAgnosticAudioCarry(carriedRaw);
// Demotion swaps only the identity; the semantics stay intact.
expect(carried.id, carriedAudioTrackId);
expect(carried.language, 'eng');
expect(carried.channels, 2);
final result = _svc(info: info).selectAudioTrack(tracks, carried);
expect(result!.priority, TrackSelectionPriority.serverSelected);
// Control: the raw (un-demoted) carry would have identity-latched the
// reused id — the exact bypass the boundary demotion exists to prevent.
final latched = _svc(info: info).selectAudioTrack(tracks, carriedRaw);
expect(latched!.priority, TrackSelectionPriority.navigation);
expect(latched.track.id, '2');
});
test('Priority 2: Plex-selected track from media info', () {
final tracks = [_audio('A', lang: 'eng'), _audio('B', lang: 'fre')];
final info = _info(
@@ -1205,6 +1220,30 @@ void main() {
];
expect(findSourceTrackForIntent(intent, rows)?.id, 2);
});
test('the semantic title outranks a retained codec across a codec flip', () {
// The signs track was re-encoded srt on this episode while the full
// dialogue track kept the old codec: the row NAMED by the carried
// title must win — technical parity only breaks ties the semantic
// tiers left.
const intent = SubtitleIntent(language: 'eng', forced: false, title: 'Signs/OP/ED', codec: 'ass');
final rows = [
_plexSub(1, languageCode: 'eng', title: 'Full Subtitles', codec: 'ass'),
_plexSub(2, languageCode: 'eng', title: 'Signs/OP/ED', codec: 'subrip'),
];
expect(findSourceTrackForIntent(intent, rows)?.id, 2);
});
test('an indistinguishable same-language pair declines rather than latching by order', () {
// A titleless carry cannot tell two equal same-language rows apart:
// guessing the first row would recreate the #1717 order latch.
const intent = SubtitleIntent(language: 'eng', forced: false, codec: 'subrip');
final rows = [
_plexSub(1, languageCode: 'eng', codec: 'subrip'),
_plexSub(2, languageCode: 'eng', codec: 'subrip'),
];
expect(findSourceTrackForIntent(intent, rows), isNull);
});
});
group('findNativeTrackForIntent', () {
@@ -1248,6 +1287,75 @@ void main() {
});
});
group('audio carry evidence bands', () {
test('bridges two- and three-letter language codes across episodes', () {
// The old carry compared languages with raw equality, so a 'sv' pick
// never found a 'swe'-tagged row on the next episode.
final rows = [_plexAudio(1, languageCode: 'eng'), _plexAudio(2, languageCode: 'swe')];
expect(findSourceAudioTrackForIntent(_audio('x', lang: 'sv'), rows)?.id, 2);
});
test('keeps the commentary/main distinction between same-language tracks', () {
// The old language-only tier returned the FIRST same-language row,
// flipping a commentary pick back to the main mix every episode.
final rows = [
_plexAudio(1, languageCode: 'eng', title: 'Main'),
_plexAudio(2, languageCode: 'eng', title: 'Commentary'),
];
expect(findSourceAudioTrackForIntent(_audio('x', lang: 'eng', title: 'Commentary'), rows)?.id, 2);
});
test('a unique title vouches for untagged tracks', () {
final rows = [_plexAudio(1, title: 'Main'), _plexAudio(2, title: 'Commentary')];
expect(findSourceAudioTrackForIntent(_audio('x', title: 'Commentary'), rows)?.id, 2);
});
test('codec parity alone never vouches for an untagged track', () {
final rows = [_plexAudio(1, codec: 'ac3')];
expect(findSourceAudioTrackForIntent(_audio('x', title: 'Commentary', codec: 'ac3'), rows), isNull);
});
test('an ambiguous same-title untagged pair declines rather than guesses', () {
final rows = [_plexAudio(1, title: 'Stereo'), _plexAudio(2, title: 'Stereo')];
expect(findSourceAudioTrackForIntent(_audio('x', title: 'Stereo'), rows), isNull);
});
test('a declared language contradiction is never rescued by a title', () {
final rows = [_plexAudio(1, languageCode: 'eng', title: 'Commentary')];
expect(findSourceAudioTrackForIntent(_audio('x', lang: 'swe', title: 'Commentary'), rows), isNull);
});
test('channel count breaks ties between otherwise equal rows', () {
final rows = [
_plexAudio(1, languageCode: 'eng', channels: 2, codec: 'aac'),
_plexAudio(2, languageCode: 'eng', channels: 6, codec: 'aac'),
];
expect(findSourceAudioTrackForIntent(_audio('x', lang: 'eng', channels: 6, codec: 'aac'), rows)?.id, 2);
});
test('the native twin skips the auto and off sentinels', () {
final tracks = [AudioTrack.auto, AudioTrack.off, _audio('3', lang: 'eng')];
expect(findNativeAudioTrackForIntent(_audio('x', lang: 'eng'), tracks)?.id, '3');
});
test('a commentary title outranks a retained codec across a codec flip', () {
final rows = [
_plexAudio(1, languageCode: 'eng', title: 'Main', codec: 'ac3'),
_plexAudio(2, languageCode: 'eng', title: 'Commentary', codec: 'aac'),
];
final carried = _audio('x', lang: 'eng', title: 'Commentary', codec: 'ac3');
expect(findSourceAudioTrackForIntent(carried, rows)?.id, 2);
});
test('an indistinguishable same-language pair declines rather than latching by order', () {
final rows = [
_plexAudio(1, languageCode: 'eng', codec: 'aac', channels: 2),
_plexAudio(2, languageCode: 'eng', codec: 'aac', channels: 2),
];
expect(findSourceAudioTrackForIntent(_audio('x', lang: 'eng', codec: 'aac'), rows), isNull);
});
});
group('selectSubtitleTrack - intent preferences (#1716/#1717)', () {
const forcedIntent = SubtitlePreference.intent(
SubtitleIntent(language: 'fre', forced: true, title: 'FR Forced [ASS]', codec: 'ass'),
@@ -53,6 +53,11 @@ void main() {
expect(tv.imdbIds, ['tt2']);
expect(index.byTmdb[456]!.single, same(tv));
expect(index.byImdb['tt2']!.single, same(tv));
// AniDB is the dataset's primary key, so it indexes to a single row —
// the only handle a HAMA-matched Plex library can offer (#1788).
expect(index.byAnidb[7], same(movie));
expect(index.byAnidb[8], same(tv));
});
test('an unexpected field shape yields null fields, not a whole-parse crash', () {
@@ -66,7 +66,7 @@ class _FakeFribbLookup implements FribbMappingLookup {
const _FakeFribbLookup(this.rows);
@override
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId}) async => rows;
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId}) async => rows;
@override
Future<FribbMappingRow?> lookupByMal(int malId) async => rows.where((row) => row.malId == malId).firstOrNull;
@@ -111,6 +111,20 @@ MediaItem _episode(int number, {int season = 1}) => testMediaItem(
index: number,
);
/// An episode that already knows its show, as playback metadata does — the
/// resolver reads the show's guids through `grandparentId`.
MediaItem _episodeOfShow(int number, {int season = 1}) => testMediaItem(
id: 'episode-$season-$number',
backend: MediaBackend.plex,
kind: MediaKind.episode,
title: 'Episode $number',
serverId: ServerId('server-1'),
libraryId: 'lib-1',
grandparentId: 'show-1',
parentIndex: season,
index: number,
);
MediaItem _show() => testMediaItem(
id: 'show-1',
backend: MediaBackend.plex,
@@ -299,6 +313,72 @@ void main() {
expect(anilistSaves, contains(equals({'mediaId': 202, 'progress': 2, 'status': 'COMPLETED'})));
});
// A HAMA-matched library identifies anime by AniDB id and nothing else, so
// every tracker used to be skipped with "no external IDs" (#1788).
test('a HAMA show identified only by AniDB still reaches MAL and AniList', () async {
await simkl.setEnabled(false);
await mal.setEnabled(true);
await anilist.setEnabled(true);
coordinator.debugUseResolverDependencies(
store: const _FakeFribbLookup([FribbMappingRow(anidbId: 11905, malId: 21, anilistId: 30, type: 'TV')]),
animeLists: const _FakeAnimeListsLookup(),
);
final malUpdates = <int, Map<String, String>>{};
final malHttp = MockClient((request) async {
final malId = int.parse(request.url.pathSegments[2]);
if (request.method == 'GET') return http.Response(json.encode({'num_episodes': 12}), 200);
expect(request.method, 'PUT');
malUpdates[malId] = Uri.splitQueryString(request.body);
return http.Response('{}', 200);
});
mal.rebindSession(_malSession(), onSessionInvalidated: () {}, httpClient: malHttp);
final anilistSaves = <Map<String, dynamic>>[];
final anilistHttp = MockClient((request) async {
final body = json.decode(request.body) as Map<String, dynamic>;
final query = body['query'] as String;
if (query.contains('Media(id:')) {
return http.Response(
json.encode({
'data': {
'Media': {'episodes': 12},
},
}),
200,
);
}
if (query.contains('SaveMediaListEntry')) {
anilistSaves.add((body['variables'] as Map).cast<String, dynamic>());
return http.Response(
json.encode({
'data': {
'SaveMediaListEntry': {'id': 1},
},
}),
200,
);
}
fail('Unexpected AniList query: $query');
});
anilist.rebindSession(_anilistSession(), onSessionInvalidated: () {}, httpClient: anilistHttp);
final client = _FakeMediaServerClient(
externalIdsByItem: {'show-1': const ExternalIds(anidb: 11905)},
descendantsByParent: const {},
);
await coordinator.markWatched(_episodeOfShow(4), client);
expect(client.externalIdCalls, ['show-1']);
expect(malUpdates, {
21: {'status': 'watching', 'num_watched_episodes': '4'},
});
expect(anilistSaves, [
{'mediaId': 30, 'progress': 4, 'status': 'CURRENT'},
]);
});
test('groups manually watched same-season split cours by Anime-Lists ranges', () async {
await simkl.setEnabled(false);
await mal.setEnabled(true);
@@ -31,12 +31,21 @@ class _FakeMediaServerClient implements MediaServerClient {
class _FakeFribbLookup implements FribbMappingLookup {
final List<FribbMappingRow> rows;
int lookups = 0;
int? lastAnidbId;
_FakeFribbLookup(this.rows);
/// Mirrors the real store: an AniDB id is the dataset's primary key and
/// resolves at most one row, so it short-circuits the tvdb/tmdb/imdb ladder.
@override
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId}) async {
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId}) async {
lookups++;
lastAnidbId = anidbId;
if (anidbId != null) {
final hit = rows.where((row) => row.anidbId == anidbId).firstOrNull;
if (hit != null) return [hit];
}
if (tvdbId == null && tmdbId == null && imdbId == null) return const [];
return rows;
}
@@ -110,9 +119,12 @@ TrackerIdResolver _resolver({
required _FakeAnimeProgressLookup animeProgress,
_FakeFribbLookup? lookup,
AnimeListsMappingLookup animeLists = const _FakeAnimeListsLookup(),
ExternalIds showIds = const ExternalIds(tvdb: 81797, tmdb: 37854, imdb: 'tt0388629'),
bool Function()? needsFribb,
}) {
return TrackerIdResolver(
_FakeMediaServerClient({'show-1': const ExternalIds(tvdb: 81797, tmdb: 37854, imdb: 'tt0388629')}),
_FakeMediaServerClient({'show-1': showIds}),
needsFribb: needsFribb,
store: lookup ?? _FakeFribbLookup(rows),
animeLists: animeLists,
animeProgress: animeProgress,
@@ -293,4 +305,97 @@ void main() {
expect(lookup.lookups, 2);
});
});
group('TrackerIdResolver AniDB-only items', () {
const hamaRow = FribbMappingRow(anidbId: 11905, malId: 21, anilistId: 30, simklId: 40, type: 'TV');
test('a HAMA show resolves its anime through the AniDB id alone', () async {
final lookup = _FakeFribbLookup(const [hamaRow]);
final resolver = _resolver(
rows: const [hamaRow],
lookup: lookup,
animeProgress: _FakeAnimeProgressLookup(4),
showIds: const ExternalIds(anidb: 11905),
);
final ids = await resolver.resolveShowForEpisode(_episode(season: 1, number: 4));
expect(lookup.lastAnidbId, 11905);
expect(ids?.anime?.mal, 21);
expect(ids?.anime?.anilist, 30);
expect(ids?.animeProgressScope, AnimeProgressScope.show);
expect(ids?.animeProgress, 4);
});
test('an AniDB id does not describe a season beside season 1', () async {
final lookup = _FakeFribbLookup(const [hamaRow]);
final resolver = _resolver(
rows: const [hamaRow],
lookup: lookup,
animeProgress: _FakeAnimeProgressLookup(null),
showIds: const ExternalIds(anidb: 11905),
);
final ids = await resolver.resolveShowForEpisode(_episode(season: 2, number: 4));
expect(lookup.lastAnidbId, isNull, reason: 'season 2 means the library is TVDB-numbered');
expect(ids?.anime?.mal, isNull);
});
test('a catalog id still wins the ladder when both are present', () async {
final lookup = _FakeFribbLookup(const [
hamaRow,
FribbMappingRow(anidbId: 222, tvdbId: 81797, malId: 999, type: 'TV'),
]);
final resolver = _resolver(
rows: const [],
lookup: lookup,
animeProgress: _FakeAnimeProgressLookup(null),
showIds: const ExternalIds(anidb: 11905, tvdb: 81797),
);
final ids = await resolver.resolveShowForEpisode(_episode(season: 1, number: 4));
expect(ids?.anime?.mal, 21, reason: 'AniDB names exactly one row, so it leads the ladder');
});
test('an item with no ids at all resolves to nothing', () async {
final resolver = _resolver(
rows: const [hamaRow],
animeProgress: _FakeAnimeProgressLookup(null),
showIds: const ExternalIds(),
);
expect(await resolver.resolveShowForEpisode(_episode(season: 1, number: 4)), isNull);
});
test('trackers that never map anime get nothing from an AniDB-only item', () async {
final resolver = _resolver(
rows: const [hamaRow],
animeProgress: _FakeAnimeProgressLookup(null),
showIds: const ExternalIds(anidb: 11905),
needsFribb: () => false,
);
expect(
await resolver.resolveShowForEpisode(_episode(season: 1, number: 4)),
isNull,
reason: 'Trakt and Simkl cannot address an AniDB id',
);
});
test('trackers that never map anime still get a catalog-id context', () async {
final resolver = _resolver(
rows: const [],
animeProgress: _FakeAnimeProgressLookup(null),
showIds: const ExternalIds(tvdb: 81797),
needsFribb: () => false,
);
final ids = await resolver.resolveShowForEpisode(_episode(season: 1, number: 4));
expect(ids?.external.tvdb, 81797);
expect(ids?.anime, isNull);
});
});
}
@@ -69,7 +69,7 @@ class _FakeFribbLookup implements FribbMappingLookup {
/// Filters by tvdb id so distinct shows map to distinct anime entries, which is
/// what makes their queued rows distinct.
@override
Future<List<FribbMappingRow>> lookup({int? tvdbId, int? tmdbId, String? imdbId}) async =>
Future<List<FribbMappingRow>> lookup({int? anidbId, int? tvdbId, int? tmdbId, String? imdbId}) async =>
rows.where((row) => tvdbId == null || row.tvdbId == tvdbId).toList();
@override
+51 -12
View File
@@ -45,27 +45,34 @@ void main() {
});
test('normalizes HAMA GUID modes with direct external IDs', () {
final cases = <({String guid, String? imdb, int? tmdb, int? tvdb})>[
(guid: 'com.plexapp.agents.hama://tvdb-315500', imdb: null, tmdb: null, tvdb: 315500),
(guid: 'com.plexapp.agents.hama://tvdb2-315500', imdb: null, tmdb: null, tvdb: 315500),
(guid: 'com.plexapp.agents.hama://tvdb9-315500', imdb: null, tmdb: null, tvdb: 315500),
(guid: 'com.plexapp.agents.hama://tmdb-69346', imdb: null, tmdb: 69346, tvdb: null),
(guid: 'com.plexapp.agents.hama://tsdb-69346?lang=en', imdb: null, tmdb: 69346, tvdb: null),
(guid: 'com.plexapp.agents.hama://imdb-6455986', imdb: 'tt6455986', tmdb: null, tvdb: null),
(guid: 'com.plexapp.agents.hama://imdb-tt6455986', imdb: 'tt6455986', tmdb: null, tvdb: null),
final cases = <({String guid, String? imdb, int? tmdb, int? tvdb, int? anidb})>[
(guid: 'com.plexapp.agents.hama://tvdb-315500', imdb: null, tmdb: null, tvdb: 315500, anidb: null),
(guid: 'com.plexapp.agents.hama://tvdb2-315500', imdb: null, tmdb: null, tvdb: 315500, anidb: null),
(guid: 'com.plexapp.agents.hama://tvdb9-315500', imdb: null, tmdb: null, tvdb: 315500, anidb: null),
(guid: 'com.plexapp.agents.hama://tmdb-69346', imdb: null, tmdb: 69346, tvdb: null, anidb: null),
(guid: 'com.plexapp.agents.hama://tsdb-69346?lang=en', imdb: null, tmdb: 69346, tvdb: null, anidb: null),
(guid: 'com.plexapp.agents.hama://imdb-6455986', imdb: 'tt6455986', tmdb: null, tvdb: null, anidb: null),
(guid: 'com.plexapp.agents.hama://imdb-tt6455986', imdb: 'tt6455986', tmdb: null, tvdb: null, anidb: null),
(guid: 'com.plexapp.agents.hama://anidb-11905?lang=en', imdb: null, tmdb: null, tvdb: null, anidb: 11905),
];
for (final testCase in cases) {
final ids = ExternalIds.fromLegacyPlexGuid(testCase.guid);
expect(
(imdb: ids.imdb, tmdb: ids.tmdb, tvdb: ids.tvdb),
(imdb: testCase.imdb, tmdb: testCase.tmdb, tvdb: testCase.tvdb),
(imdb: ids.imdb, tmdb: ids.tmdb, tvdb: ids.tvdb, anidb: ids.anidb),
(imdb: testCase.imdb, tmdb: testCase.tmdb, tvdb: testCase.tvdb, anidb: testCase.anidb),
reason: testCase.guid,
);
}
});
test('rejects unsupported agents, AniDB modes, and malformed IDs', () {
test('an AniDB id is not a catalog id', () {
final ids = ExternalIds.fromLegacyPlexGuid('com.plexapp.agents.hama://anidb-11905');
expect(ids.hasAny, isTrue);
expect(ids.hasCatalogIds, isFalse, reason: 'IMDb/TMDB/TVDB consumers must not act on an AniDB id');
});
test('rejects unsupported agents, AniDB grouping modes, and malformed IDs', () {
final invalid = <Object?>[
null,
315500,
@@ -74,7 +81,12 @@ void main() {
'plex://movie/abc',
'local://315500',
'com.plexapp.agents.none://315500',
'com.plexapp.agents.hama://anidb-11905',
// anidb2..9 group several AniDB entries under one TVDB-numbered Plex
// show, so the guid's id does not describe the seasons beside it.
'com.plexapp.agents.hama://anidb2-11905',
'com.plexapp.agents.hama://anidb9-11905',
'com.plexapp.agents.hama://anidb-not-a-number',
'com.plexapp.agents.hama://anidb-',
'com.plexapp.agents.hama://tvdb10-315500',
'com.plexapp.agents.hama://tvdb-not-a-number',
'com.plexapp.agents.hama://tmdb-',
@@ -88,6 +100,33 @@ void main() {
});
});
group('ExternalIds.fillFrom', () {
test('keeps its own ids and only fills the ones it is missing', () {
const modern = ExternalIds(tvdb: 315500);
const legacy = ExternalIds(imdb: 'tt6455986', tvdb: 999, anidb: 11905);
final merged = modern.fillFrom(legacy);
expect(merged.tvdb, 315500, reason: 'the modern Guid array wins per field');
expect(merged.imdb, 'tt6455986');
expect(merged.anidb, 11905);
});
test('round-trips every id through JSON', () {
const ids = ExternalIds(imdb: 'tt1', tmdb: 2, tvdb: 3, anidb: 4);
final restored = ExternalIds.fromJson(ids.toJson());
expect((restored.imdb, restored.tmdb, restored.tvdb, restored.anidb), ('tt1', 2, 3, 4));
expect(ExternalIds.fromJson(const ExternalIds().toJson()).hasAny, isFalse);
});
test('intersects matches on an AniDB id alone', () {
const hama = ExternalIds(anidb: 11905);
expect(hama.intersects(const ExternalIds(anidb: 11905)), isTrue);
expect(hama.intersects(const ExternalIds(tvdb: 315500)), isFalse);
});
});
group('ExternalIds.fromJellyfinProviderIds', () {
test('extracts Tmdb/Imdb/Tvdb (case-insensitive)', () {
final ids = ExternalIds.fromJellyfinProviderIds({'Tmdb': '12345', 'Imdb': 'tt99999', 'Tvdb': '777'});