Files backend: release-name parser, video-only scanner, folder store, mpv thumbnails
lib/src/files/ for the 1.0 Files source (UI comes with the library round; ARCHITECTURE gets its section then): - parseReleaseName: series/season/episode/group/year/extras from release names (fansub, scene, batch, NCOP/OVA markers); seriesKey for grouping. - scanFolder (isolate): videos only, samples/trailers and other files counted as hidden, sidecar subtitles paired by name (+ language/flag suffixes), 20 000-file cap; groupBySeries -> series + loose videos. - FolderStore: watched folders and recent files in Hive, as signals. - thumbnailFor: a 480 px JPEG at 25% via a hidden mpv player (screenshot-to-file, vo=null), cached by path+size+mtime, 2 at a time, cancellable, never throws. No ffmpeg needed (Windows ships only libmpv). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6f136bfc4d
commit
c76fee70dc
8 files changed
+1181
No files matched your search
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:hive_ce/hive.dart';
|
||||
import 'package:signals/signals_flutter.dart';
|
||||
|
||||
// Files source state, one Hive box: the folders the user added and the
|
||||
// local files played last. Same shape as AppSettings: signals start empty,
|
||||
// take the stored values once [FolderStore.ensureLoaded] finishes, and
|
||||
// mutators write through.
|
||||
|
||||
const filesBoxName = 'files';
|
||||
|
||||
const _keyFolders = 'folders';
|
||||
const _keyRecent = 'recent';
|
||||
|
||||
/// Recent files kept, most recent first.
|
||||
const maxRecentFiles = 30;
|
||||
|
||||
class FolderStore {
|
||||
static final FolderStore instance = FolderStore();
|
||||
|
||||
/// Watched folders, in the order they were added.
|
||||
final folders = signal<List<String>>(const []);
|
||||
/// Local files played, most recent first, no duplicates.
|
||||
final recent = signal<List<String>>(const []);
|
||||
|
||||
Future<void>? _load;
|
||||
Box? _box;
|
||||
|
||||
Future<void> ensureLoaded() => _load ??= _loadNow();
|
||||
|
||||
Future<void> _loadNow() async {
|
||||
try {
|
||||
final box = _box = await Hive.openBox(filesBoxName);
|
||||
final f = box.get(_keyFolders);
|
||||
if (f is List) folders.value = List.unmodifiable(f.whereType<String>());
|
||||
final r = box.get(_keyRecent);
|
||||
if (r is List) {
|
||||
recent.value = List.unmodifiable(
|
||||
r.whereType<String>().toSet().take(maxRecentFiles));
|
||||
}
|
||||
} catch (e, st) {
|
||||
debugPrint('load files store failed: $e\n$st');
|
||||
}
|
||||
}
|
||||
|
||||
/// False when [dir] is already watched.
|
||||
bool addFolder(String dir) {
|
||||
if (folders.value.contains(dir)) return false;
|
||||
_setFolders([...folders.value, dir]);
|
||||
return true;
|
||||
}
|
||||
|
||||
void removeFolder(String dir) =>
|
||||
_setFolders([...folders.value.where((d) => d != dir)]);
|
||||
|
||||
/// Moves [path] to the top of [recent].
|
||||
void addRecent(String path) => _setRecent(
|
||||
[path, ...recent.value.where((p) => p != path)].take(maxRecentFiles));
|
||||
|
||||
void removeRecent(String path) =>
|
||||
_setRecent(recent.value.where((p) => p != path));
|
||||
|
||||
void clearRecent() => _setRecent(const []);
|
||||
|
||||
void _setFolders(List<String> list) {
|
||||
folders.value = List.unmodifiable(list);
|
||||
_put(_keyFolders, [...list]);
|
||||
}
|
||||
|
||||
void _setRecent(Iterable<String> list) {
|
||||
recent.value = List.unmodifiable(list);
|
||||
_put(_keyRecent, [...recent.value]);
|
||||
}
|
||||
|
||||
Future<void> _put(String key, Object value) async {
|
||||
try {
|
||||
final box = _box ??
|
||||
(Hive.isBoxOpen(filesBoxName) ? Hive.box(filesBoxName) : null);
|
||||
await box?.put(key, value);
|
||||
} catch (e, st) {
|
||||
debugPrint('save files store $key failed: $e\n$st');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
// Release file names -> series / season / episode, anitomy-style but small:
|
||||
// enough to group a downloads folder into shows. Unknown shapes fall back to
|
||||
// the cleaned name with no episode, never to a wrong number.
|
||||
|
||||
/// What a release file name says.
|
||||
class ParsedName {
|
||||
/// Title without group, season marker, episode, year or release tags.
|
||||
final String series;
|
||||
final int? season;
|
||||
final int? episode;
|
||||
/// Release group: leading `[Group]` or scene-style trailing `-GRP`.
|
||||
final String? group;
|
||||
/// Release year, taken out of [series] (movies, `Title (2019)`).
|
||||
final int? year;
|
||||
/// Non-episode marker (`NCOP1`, `NCED`, `OVA 2`, `Special`): such files
|
||||
/// carry no [episode] so they never sort among the real ones.
|
||||
final String? extra;
|
||||
|
||||
const ParsedName(
|
||||
this.series, {
|
||||
this.season,
|
||||
this.episode,
|
||||
this.group,
|
||||
this.year,
|
||||
this.extra,
|
||||
});
|
||||
|
||||
/// `S01E03`, `E25`, the [extra] marker, `S02` for a season pack, else ''.
|
||||
String get label {
|
||||
final s = season == null ? '' : 'S${season.toString().padLeft(2, '0')}';
|
||||
if (episode != null) return '${s}E${episode.toString().padLeft(2, '0')}';
|
||||
return extra ?? s;
|
||||
}
|
||||
|
||||
/// Grouping key: case, punctuation and spacing do not split a series.
|
||||
String get seriesKey => normalizeSeries(series);
|
||||
|
||||
@override
|
||||
String toString() => 'ParsedName($series, s=$season, e=$episode, '
|
||||
'group=$group, year=$year, extra=$extra)';
|
||||
}
|
||||
|
||||
/// Lowercase letters and digits of [s], single spaces between words.
|
||||
String normalizeSeries(String s) => s
|
||||
.toLowerCase()
|
||||
.replaceAll(RegExp(r"['’`]"), '')
|
||||
.replaceAll(RegExp(r'[^\p{L}\p{N}]+', unicode: true), ' ')
|
||||
.trim();
|
||||
|
||||
// Release tags: the title ends where the first of these starts.
|
||||
final _junk = RegExp(
|
||||
r'\b(?:2160p|1440p|1080[pi]|720p|576p|480p|4K|UHD|[xh]\.?26[45]|HEVC|AVC|'
|
||||
r'AV1|VP9|WEB(?:-?DL|-?Rip)?|BD(?:Rip|Remux)?|Blu-?Ray|BRRip|DVD(?:Rip)?|'
|
||||
r'HDTV|HDR(?:10)?|DV|REMUX|AAC(?:\d\.\d)?|FLAC|Opus|DTS(?:-HD)?|E?-?AC-?3|'
|
||||
r'DDP?\d?|TrueHD|Atmos|10-?bit|8-?bit|Hi10P?|PROPER|REPACK|Dual[ -]Audio|'
|
||||
r'Multi(?:ple)?[ -]Subs?(?:titles?)?|AMZN|NF|CR|DSNP|HMAX|ATVP|'
|
||||
r'Batch|Complete)\b',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final _ext = RegExp(r'\.(?=[a-z0-9]*[a-z])[a-z0-9]{2,4}$', caseSensitive: false);
|
||||
final _leadingGroup = RegExp(r'^\s*\[([^\]]+)\]');
|
||||
final _sceneGroup = RegExp(r'-([A-Za-z0-9]+)$');
|
||||
final _bracketYear = RegExp(r'[(\[]((?:19|20)\d{2})[)\]]');
|
||||
final _brackets = RegExp(r'\[[^\]]*\]|\([^)]*\)|\{[^}]*\}|【[^】]*】');
|
||||
// S01E02, S01.E02, S1 E2; a batch `S01E01-E02` / `S01E01E02` keeps the first.
|
||||
final _sxe = RegExp(r'\bS(\d{1,2})[ .]?E(\d{1,4})(?:v\d)?(?!\d)',
|
||||
caseSensitive: false);
|
||||
final _nxn = RegExp(r'\b(\d{1,2})x(\d{2,3})\b');
|
||||
// Anime: `Title - 25`, `- 03v2`, `- 01-02` (batch keeps the first).
|
||||
final _dashNumber = RegExp(r'\s[-–]\s(\d{1,4})(?:v\d)?(?=$|[\s\-~.])');
|
||||
final _episodeWord = RegExp(
|
||||
r'\b(?:Episode|Ep\.?|E)\s?(\d{1,4})(?:v\d)?\b',
|
||||
caseSensitive: false,
|
||||
);
|
||||
// Extras: unambiguous words anywhere, short ones only right after the dash.
|
||||
final _extraAnywhere = RegExp(
|
||||
r'(?:^|\s)(NCOP|NCED|OVA|OAD|ONA)\s?(\d{1,2})?(?:v\d)?(?=$|\s)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final _extraAfterDash = RegExp(
|
||||
r'\s[-–]\s(OP|ED|SP|Specials?|Extras?|Recap|Preview|PV|Menu)\s?(\d{1,2})?'
|
||||
r'(?:v\d)?(?=$|\s)',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final _seasonInTitle = RegExp(
|
||||
r'\s(?:S(\d{1,2})|Season\s?(\d{1,2})|(\d{1,2})(?:st|nd|rd|th)\s+Season)\s*$',
|
||||
caseSensitive: false,
|
||||
);
|
||||
final _trailingYear = RegExp(r'\s((?:19|20)\d{2})$');
|
||||
|
||||
/// Parses a file name (with or without the extension, no directories).
|
||||
ParsedName parseReleaseName(String fileName) {
|
||||
var s = fileName.replaceFirst(_ext, '').trim();
|
||||
final original = s;
|
||||
String? group = _leadingGroup.firstMatch(s)?.group(1)?.trim();
|
||||
int? year;
|
||||
final by = _bracketYear.firstMatch(s);
|
||||
if (by != null) year = int.parse(by.group(1)!);
|
||||
s = s.replaceAll(_brackets, ' ');
|
||||
|
||||
// Dots and underscores as separators (scene style), unless the name
|
||||
// already has spaces and only the odd `Dr. Stone` dot.
|
||||
final dotted = !s.contains(' ') || RegExp(r'\w\.\w').allMatches(s).length > 2;
|
||||
if (dotted) {
|
||||
// `...H264-GRP`, but not `...WEB-DL`.
|
||||
final tags = _junk.allMatches(s);
|
||||
if (group == null && tags.isNotEmpty && tags.last.end < s.length) {
|
||||
final g = _sceneGroup.firstMatch(s);
|
||||
if (g != null) {
|
||||
group = g.group(1);
|
||||
s = s.substring(0, g.start);
|
||||
}
|
||||
}
|
||||
s = s.replaceAll('.', ' ');
|
||||
}
|
||||
s = s.replaceAll('_', ' ').replaceAll(RegExp(r'\s+'), ' ').trim();
|
||||
|
||||
// Release tags end the interesting part.
|
||||
final junk = _junk.firstMatch(s);
|
||||
if (junk != null && junk.start > 0) s = s.substring(0, junk.start).trim();
|
||||
|
||||
int? season, episode;
|
||||
String? extra;
|
||||
var cut = s.length;
|
||||
final extraMatch =
|
||||
_extraAfterDash.firstMatch(s) ?? _extraAnywhere.firstMatch(s);
|
||||
final sxe = _sxe.firstMatch(s);
|
||||
if (extraMatch != null) {
|
||||
final word = extraMatch.group(1)!;
|
||||
final upper = word.length <= 4 ? word.toUpperCase() : _title(word);
|
||||
// `OVA - 02`: the number may follow the dash instead.
|
||||
final n = extraMatch.group(2) ??
|
||||
_dashNumber.firstMatch(s.substring(extraMatch.end))?.group(1);
|
||||
extra = n == null
|
||||
? upper
|
||||
: (upper.startsWith('NC') || upper.length <= 2)
|
||||
? '$upper${int.parse(n)}'
|
||||
: '$upper ${int.parse(n)}';
|
||||
cut = extraMatch.start;
|
||||
if (sxe != null && sxe.start < cut) {
|
||||
season = int.parse(sxe.group(1)!);
|
||||
cut = sxe.start;
|
||||
}
|
||||
} else if (sxe != null) {
|
||||
season = int.parse(sxe.group(1)!);
|
||||
episode = int.parse(sxe.group(2)!);
|
||||
cut = sxe.start;
|
||||
} else {
|
||||
final nxn = _nxn.firstMatch(s);
|
||||
if (nxn != null) {
|
||||
season = int.parse(nxn.group(1)!);
|
||||
episode = int.parse(nxn.group(2)!);
|
||||
cut = nxn.start;
|
||||
} else {
|
||||
final m = _dashNumber.firstMatch(s) ?? _episodeWord.firstMatch(s);
|
||||
if (m != null) {
|
||||
episode = int.parse(m.group(1)!);
|
||||
cut = m.start;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var series = s.substring(0, cut);
|
||||
// Season pack or season marker kept in the title: `Title S2`,
|
||||
// `Title Season 2`, `Title 2nd Season`, `Title.S01.1080p`.
|
||||
final sIn = _seasonInTitle.firstMatch(series);
|
||||
if (sIn != null) {
|
||||
season ??= int.parse(sIn.group(1) ?? sIn.group(2) ?? sIn.group(3)!);
|
||||
series = series.substring(0, sIn.start);
|
||||
}
|
||||
series = series.replaceAll(RegExp(r'[\s\-–:,~]+$'), '').trim();
|
||||
// A trailing year is the release year, unless it is the whole title or
|
||||
// too far ahead to be one (`Blade Runner 2049`).
|
||||
final ty = _trailingYear.firstMatch(series);
|
||||
if (ty != null) {
|
||||
final y = int.parse(ty.group(1)!);
|
||||
if (y <= DateTime.now().year + 1) {
|
||||
year ??= y;
|
||||
series = series.substring(0, ty.start).trim();
|
||||
}
|
||||
}
|
||||
series = series.replaceAll(RegExp(r'[\s\-–:,~]+$'), '').trim();
|
||||
if (series.isEmpty) {
|
||||
series = original.replaceAll(RegExp(r'[._]+'), ' ').trim();
|
||||
}
|
||||
return ParsedName(
|
||||
series,
|
||||
season: season,
|
||||
episode: episode,
|
||||
group: group,
|
||||
year: year,
|
||||
extra: extra,
|
||||
);
|
||||
}
|
||||
|
||||
String _title(String w) => w[0].toUpperCase() + w.substring(1).toLowerCase();
|
||||
@@ -0,0 +1,257 @@
|
||||
import 'dart:io';
|
||||
import 'dart:isolate';
|
||||
|
||||
import 'name_parser.dart';
|
||||
|
||||
// Folder scan for the Files source: videos with their parsed names,
|
||||
// sidecar subtitles, everything else counted and hidden. The walk is
|
||||
// synchronous I/O, so it runs in its own isolate.
|
||||
|
||||
const videoExtensions = {
|
||||
'mkv', 'mp4', 'webm', 'avi', 'mov', 'm4v', 'ts', 'm2ts', 'wmv', 'flv', //
|
||||
};
|
||||
const subtitleExtensions = {'ass', 'ssa', 'srt', 'vtt', 'sup'};
|
||||
|
||||
/// Files looked at per scan; past this the result is [FolderScan.truncated].
|
||||
const maxScannedFiles = 20000;
|
||||
|
||||
/// Samples and trailers under this size are hidden next to the real thing.
|
||||
const _sampleMaxBytes = 300 << 20;
|
||||
|
||||
enum FileKind { video, subtitle, other }
|
||||
|
||||
FileKind kindOf(String path) {
|
||||
final ext = _extension(_baseName(path));
|
||||
if (videoExtensions.contains(ext)) return FileKind.video;
|
||||
if (subtitleExtensions.contains(ext)) return FileKind.subtitle;
|
||||
return FileKind.other;
|
||||
}
|
||||
|
||||
class VideoFile {
|
||||
final String path;
|
||||
final int size;
|
||||
final ParsedName parsed;
|
||||
final DateTime modified;
|
||||
const VideoFile(this.path, this.size, this.parsed, this.modified);
|
||||
|
||||
String get name => _baseName(path);
|
||||
}
|
||||
|
||||
class FolderScan {
|
||||
final List<VideoFile> videos;
|
||||
/// Non-video files and samples (subtitles and dot-entries not counted).
|
||||
final int hiddenCount;
|
||||
/// Up to 6 of the hidden file names, for "and N other files" hints.
|
||||
final List<String> hiddenExamples;
|
||||
/// Video path -> subtitle files next to it with the same base name
|
||||
/// (`Ep 01.mkv` -> `Ep 01.srt`, `Ep 01.en.ass`).
|
||||
final Map<String, List<String>> subtitles;
|
||||
/// Stopped after [maxScannedFiles] files.
|
||||
final bool truncated;
|
||||
|
||||
const FolderScan({
|
||||
required this.videos,
|
||||
required this.hiddenCount,
|
||||
required this.hiddenExamples,
|
||||
required this.subtitles,
|
||||
required this.truncated,
|
||||
});
|
||||
|
||||
static const empty = FolderScan(
|
||||
videos: [],
|
||||
hiddenCount: 0,
|
||||
hiddenExamples: [],
|
||||
subtitles: {},
|
||||
truncated: false,
|
||||
);
|
||||
}
|
||||
|
||||
/// Scans [dir] recursively off the UI isolate. Symlinks are not followed,
|
||||
/// hidden (dot) files and folders are skipped, unreadable subfolders are
|
||||
/// left out; never throws (a missing folder is [FolderScan.empty]).
|
||||
Future<FolderScan> scanFolder(String dir, {int maxFiles = maxScannedFiles}) =>
|
||||
Isolate.run(() => scanFolderSync(dir, maxFiles: maxFiles))
|
||||
.catchError((Object _) => FolderScan.empty);
|
||||
|
||||
/// The walk behind [scanFolder]; blocks, so call it from an isolate.
|
||||
FolderScan scanFolderSync(String dir, {int maxFiles = maxScannedFiles}) {
|
||||
final videos = <VideoFile>[];
|
||||
final subs = <String>[];
|
||||
final examples = <String>[];
|
||||
var hidden = 0, seen = 0;
|
||||
var truncated = false;
|
||||
final pending = [Directory(dir)];
|
||||
walk:
|
||||
while (pending.isNotEmpty) {
|
||||
final List<FileSystemEntity> entries;
|
||||
try {
|
||||
entries = pending.removeLast().listSync(followLinks: false);
|
||||
} catch (_) {
|
||||
continue;
|
||||
}
|
||||
entries.sort((a, b) => a.path.compareTo(b.path));
|
||||
for (final e in entries) {
|
||||
final name = _baseName(e.path);
|
||||
if (name.startsWith('.')) continue;
|
||||
if (e is Directory) {
|
||||
pending.add(e);
|
||||
continue;
|
||||
}
|
||||
if (e is! File) continue; // links
|
||||
if (++seen > maxFiles) {
|
||||
truncated = true;
|
||||
break walk;
|
||||
}
|
||||
final kind = kindOf(name);
|
||||
if (kind == FileKind.subtitle) {
|
||||
subs.add(e.path);
|
||||
continue;
|
||||
}
|
||||
FileStat? stat;
|
||||
if (kind == FileKind.video) {
|
||||
try {
|
||||
stat = e.statSync();
|
||||
} catch (_) {}
|
||||
}
|
||||
final size = stat?.size ?? 0;
|
||||
final lower = name.toLowerCase();
|
||||
final sample = kind == FileKind.video &&
|
||||
(lower.contains('sample') || lower.contains('trailer')) &&
|
||||
size < _sampleMaxBytes;
|
||||
if (kind != FileKind.video || sample) {
|
||||
hidden++;
|
||||
if (examples.length < 6) examples.add(name);
|
||||
continue;
|
||||
}
|
||||
videos.add(VideoFile(e.path, size, parseReleaseName(name),
|
||||
stat?.modified ?? DateTime.fromMillisecondsSinceEpoch(0)));
|
||||
}
|
||||
}
|
||||
return FolderScan(
|
||||
videos: videos,
|
||||
hiddenCount: hidden,
|
||||
hiddenExamples: examples,
|
||||
subtitles: _sidecars(videos, subs),
|
||||
truncated: truncated,
|
||||
);
|
||||
}
|
||||
|
||||
/// Subtitles in the same folder whose name is the video's base name,
|
||||
/// optionally followed by `.lang` / `.forced` style suffixes.
|
||||
Map<String, List<String>> _sidecars(List<VideoFile> videos, List<String> subs) {
|
||||
final byStem = <String, List<String>>{};
|
||||
for (final s in subs) {
|
||||
final stem = _stripExtension(s);
|
||||
byStem.putIfAbsent(stem, () => []).add(s);
|
||||
// `Ep 01.en.ass`, `Ep 01.en.forced.ass`: also index the shorter stems.
|
||||
var shorter = stem;
|
||||
for (var i = 0; i < 2; i++) {
|
||||
final dot = shorter.lastIndexOf('.');
|
||||
if (dot <= shorter.lastIndexOf(RegExp(r'[/\\]')) + 1) break;
|
||||
final suffix = shorter.substring(dot + 1);
|
||||
// Language / flag tags only (en, eng, pt-BR, forced, sdh): a suffix
|
||||
// with digits is part of the name (`Show.S01E01.srt` is not `Show`'s).
|
||||
if (!RegExp(r'^[A-Za-z]{2,8}(-[A-Za-z]{2,4})?$').hasMatch(suffix)) break;
|
||||
shorter = shorter.substring(0, dot);
|
||||
byStem.putIfAbsent(shorter, () => []).add(s);
|
||||
}
|
||||
}
|
||||
return {
|
||||
for (final v in videos)
|
||||
if (byStem[_stripExtension(v.path)] case final list?)
|
||||
v.path: (list.toSet().toList()..sort()),
|
||||
};
|
||||
}
|
||||
|
||||
/// One show: its episodes in season/episode order plus its extras
|
||||
/// (NCOP, OVA...) in name order.
|
||||
class SeriesGroup {
|
||||
/// Display title: the most common spelling among the files.
|
||||
final String title;
|
||||
final String key;
|
||||
final List<VideoFile> episodes;
|
||||
final List<VideoFile> extras;
|
||||
const SeriesGroup(this.title, this.key, this.episodes, this.extras);
|
||||
|
||||
/// Distinct seasons, ascending; files without one count as season 1.
|
||||
List<int> get seasons =>
|
||||
({for (final e in episodes) e.parsed.season ?? 1}.toList()..sort());
|
||||
}
|
||||
|
||||
/// [groupBySeries] result: shows, and videos that are not episodes.
|
||||
class GroupedVideos {
|
||||
final List<SeriesGroup> series;
|
||||
final List<VideoFile> loose;
|
||||
const GroupedVideos(this.series, this.loose);
|
||||
}
|
||||
|
||||
/// Groups videos with an episode number (or an extra marker) by
|
||||
/// [ParsedName.seriesKey]; the rest (movies, clips) stay loose, by name.
|
||||
/// An extra whose series has no episodes in the list is loose too.
|
||||
GroupedVideos groupBySeries(Iterable<VideoFile> videos) {
|
||||
final episodes = <String, List<VideoFile>>{};
|
||||
final extras = <String, List<VideoFile>>{};
|
||||
final loose = <VideoFile>[];
|
||||
for (final v in videos) {
|
||||
final p = v.parsed;
|
||||
final key = p.seriesKey;
|
||||
if (p.episode != null && key.isNotEmpty) {
|
||||
episodes.putIfAbsent(key, () => []).add(v);
|
||||
} else if (p.extra != null && key.isNotEmpty) {
|
||||
extras.putIfAbsent(key, () => []).add(v);
|
||||
} else {
|
||||
loose.add(v);
|
||||
}
|
||||
}
|
||||
for (final e in extras.entries) {
|
||||
if (!episodes.containsKey(e.key)) loose.addAll(e.value);
|
||||
}
|
||||
int byName(VideoFile a, VideoFile b) =>
|
||||
a.name.toLowerCase().compareTo(b.name.toLowerCase());
|
||||
final groups = [
|
||||
for (final e in episodes.entries)
|
||||
SeriesGroup(
|
||||
_commonTitle(e.value),
|
||||
e.key,
|
||||
e.value..sort(_byEpisode),
|
||||
(extras[e.key] ?? [])..sort(byName),
|
||||
),
|
||||
]..sort((a, b) => a.title.toLowerCase().compareTo(b.title.toLowerCase()));
|
||||
return GroupedVideos(groups, loose..sort(byName));
|
||||
}
|
||||
|
||||
int _byEpisode(VideoFile a, VideoFile b) {
|
||||
final pa = a.parsed, pb = b.parsed;
|
||||
final s = (pa.season ?? 1).compareTo(pb.season ?? 1);
|
||||
if (s != 0) return s;
|
||||
final e = pa.episode!.compareTo(pb.episode!);
|
||||
if (e != 0) return e;
|
||||
// Same episode twice (v2, another group): newest release first.
|
||||
return b.name.compareTo(a.name);
|
||||
}
|
||||
|
||||
String _commonTitle(List<VideoFile> files) {
|
||||
final counts = <String, int>{};
|
||||
for (final f in files) {
|
||||
counts.update(f.parsed.series, (n) => n + 1, ifAbsent: () => 1);
|
||||
}
|
||||
return counts.entries
|
||||
.reduce((a, b) => b.value > a.value ? b : a)
|
||||
.key;
|
||||
}
|
||||
|
||||
String _baseName(String path) {
|
||||
final i = path.lastIndexOf(RegExp(r'[/\\]'));
|
||||
return i < 0 ? path : path.substring(i + 1);
|
||||
}
|
||||
|
||||
String _extension(String name) {
|
||||
final dot = name.lastIndexOf('.');
|
||||
return dot <= 0 ? '' : name.substring(dot + 1).toLowerCase();
|
||||
}
|
||||
|
||||
String _stripExtension(String path) {
|
||||
final dot = path.lastIndexOf('.');
|
||||
final sep = path.lastIndexOf(RegExp(r'[/\\]'));
|
||||
return dot > sep + 1 ? path.substring(0, dot) : path;
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:media_kit/media_kit.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
// Poster frames for the Files source, made by mpv itself (no ffmpeg on
|
||||
// users' machines; Windows ships only libmpv). A hidden player per file
|
||||
// with `vo=null`: mpv still keeps the last decoded frame, so
|
||||
// `screenshot-to-file` encodes it with mpv's own JPEG writer. `start=25%`
|
||||
// makes the first decoded frame the one we want, `vf=scale` keeps it
|
||||
// small. Results (and failures) are cached on disk by path+size+mtime.
|
||||
|
||||
class Thumbnail {
|
||||
/// JPEG on disk, at most [thumbnailWidth] wide.
|
||||
final String imagePath;
|
||||
final Duration duration;
|
||||
const Thumbnail(this.imagePath, this.duration);
|
||||
}
|
||||
|
||||
const thumbnailWidth = 480;
|
||||
|
||||
/// Where thumbnails are cached; swapped in tests.
|
||||
Future<Directory> Function() thumbnailCacheRoot = getApplicationCacheDirectory;
|
||||
|
||||
/// Generations running at once: each is a full decoder.
|
||||
const _maxConcurrent = 2;
|
||||
const _timeout = Duration(seconds: 20);
|
||||
|
||||
int _running = 0;
|
||||
final _waiting = <Completer<void>>[];
|
||||
final _inFlight = <String, Future<Thumbnail?>>{};
|
||||
|
||||
/// The cached or freshly made thumbnail of the video at [path], or null
|
||||
/// when it can't be made (not a video, unreadable, timed out, cancelled).
|
||||
/// Never throws. [cancelled] is checked while queued and before the
|
||||
/// expensive steps: a scrolled-away tile returns null without decoding.
|
||||
Future<Thumbnail?> thumbnailFor(String path, {bool Function()? cancelled}) {
|
||||
final existing = _inFlight[path];
|
||||
if (existing != null) return existing;
|
||||
final f = _thumbnailFor(path, cancelled ?? () => false).catchError((
|
||||
Object e,
|
||||
StackTrace st,
|
||||
) {
|
||||
debugPrint('thumbnail $path failed: $e\n$st');
|
||||
return null;
|
||||
});
|
||||
_inFlight[path] = f;
|
||||
f.whenComplete(() => _inFlight.remove(path));
|
||||
return f;
|
||||
}
|
||||
|
||||
/// Cache key: the same file at the same size and mtime reuses its frame.
|
||||
String thumbnailKey(String path, int size, DateTime modified) => sha1
|
||||
.convert(utf8.encode('$path|$size|${modified.millisecondsSinceEpoch}'))
|
||||
.toString();
|
||||
|
||||
Future<Thumbnail?> _thumbnailFor(String path, bool Function() cancelled) async {
|
||||
final stat = await File(path).stat();
|
||||
if (stat.type != FileSystemEntityType.file) return null;
|
||||
final dir = Directory(
|
||||
'${(await thumbnailCacheRoot()).path}${Platform.pathSeparator}thumbnails');
|
||||
await dir.create(recursive: true);
|
||||
final base =
|
||||
'${dir.path}${Platform.pathSeparator}${thumbnailKey(path, stat.size, stat.modified)}';
|
||||
final cached = await _readCache(base);
|
||||
if (cached != null) return cached.$1;
|
||||
|
||||
if (cancelled()) return null;
|
||||
await _acquire();
|
||||
try {
|
||||
if (cancelled()) return null;
|
||||
final made = await _generate(path, '$base.jpg', cancelled)
|
||||
.timeout(_timeout, onTimeout: () => null);
|
||||
if (made == null) {
|
||||
// Remember broken files, not cancellations.
|
||||
if (!cancelled()) await File('$base.json').writeAsString('{}');
|
||||
return null;
|
||||
}
|
||||
await File('$base.json')
|
||||
.writeAsString(jsonEncode({'ms': made.duration.inMilliseconds}));
|
||||
return made;
|
||||
} finally {
|
||||
_release();
|
||||
}
|
||||
}
|
||||
|
||||
/// (thumbnail or null for a remembered failure), or null when not cached.
|
||||
Future<(Thumbnail?,)?> _readCache(String base) async {
|
||||
try {
|
||||
final meta = File('$base.json');
|
||||
if (!await meta.exists()) return null;
|
||||
final ms = (jsonDecode(await meta.readAsString()) as Map)['ms'];
|
||||
if (ms is! int) return (null,);
|
||||
final jpg = File('$base.jpg');
|
||||
if (!await jpg.exists()) return null;
|
||||
return (Thumbnail(jpg.path, Duration(milliseconds: ms)),);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _acquire() async {
|
||||
if (_running < _maxConcurrent) {
|
||||
_running++;
|
||||
return;
|
||||
}
|
||||
final c = Completer<void>();
|
||||
_waiting.add(c);
|
||||
await c.future; // the releaser hands its slot over
|
||||
}
|
||||
|
||||
void _release() {
|
||||
if (_waiting.isNotEmpty) {
|
||||
_waiting.removeAt(0).complete();
|
||||
} else {
|
||||
_running--;
|
||||
}
|
||||
}
|
||||
|
||||
Future<Thumbnail?> _generate(
|
||||
String path,
|
||||
String out,
|
||||
bool Function() cancelled,
|
||||
) async {
|
||||
final player = Player(
|
||||
configuration: const PlayerConfiguration(
|
||||
vo: 'null',
|
||||
muted: true,
|
||||
osc: false,
|
||||
libass: false,
|
||||
title: 'thumbnail',
|
||||
bufferSize: 4 << 20,
|
||||
),
|
||||
);
|
||||
try {
|
||||
final mpv = player.platform as NativePlayer;
|
||||
for (final (k, v) in [
|
||||
('ao', 'null'),
|
||||
('aid', 'no'),
|
||||
('sid', 'no'),
|
||||
('vid', 'auto'), // media_kit starts with vid=no
|
||||
('hwdec', 'no'),
|
||||
('cache', 'no'),
|
||||
('hr-seek', 'no'), // nearest keyframe is fine for a poster
|
||||
('start', '25%'),
|
||||
('vf', 'scale=w=$thumbnailWidth:h=-2'),
|
||||
('screenshot-format', 'jpg'),
|
||||
('screenshot-jpeg-quality', '85'),
|
||||
('screenshot-tag-colorspace', 'no'),
|
||||
]) {
|
||||
await mpv.setProperty(k, v);
|
||||
}
|
||||
await player.open(Media(path), play: false);
|
||||
final target = File(out);
|
||||
final deadline = DateTime.now().add(_timeout);
|
||||
while (DateTime.now().isBefore(deadline)) {
|
||||
if (cancelled()) return null;
|
||||
// Unreadable or no video (with aid=no, audio-only stops too): mpv
|
||||
// drops the file and goes idle at once.
|
||||
if (await mpv.getProperty('idle-active') == 'yes') return null;
|
||||
// A frame is up once the video has a size and the seek is done.
|
||||
final w = await mpv.getProperty('video-params/w');
|
||||
final seeking = await mpv.getProperty('seeking');
|
||||
if (w.isNotEmpty && w != '0' && seeking != 'yes') {
|
||||
await mpv.command(['screenshot-to-file', out, 'video']);
|
||||
if (await target.exists() && await target.length() > 0) {
|
||||
final d = double.tryParse(await mpv.getProperty('duration')) ?? 0;
|
||||
return Thumbnail(out, Duration(milliseconds: (d * 1000).round()));
|
||||
}
|
||||
}
|
||||
await Future.delayed(const Duration(milliseconds: 50));
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
await player.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user