JA
apps/winzik / src / Model / Playlist.php · commit 6576d6f
<?phpnamespace App\Model;/** * The play list (Form2.List1 of 2001): the files, the one playing (actif), the shuffle (Hasard) and the .FLS files. * Next / previous work as in the old player: the end of the list goes back to the start, the start to the end, * and with Hasard on any line can come. */final class Playlist{    /** extensions shown with their own icon in the list */    public const AUDIO = ['mp3', 'wav', 'mid', 'midi', 'ogg', 'flac'];    /** films: their sound and pictures are made by ffmpeg (App\Media\VideoCache), the desktop version only */    public const VIDEO = ['mp4', 'webm', 'mkv'];    /** @var list<string> */    public array $items = [];    /** the line playing, -1 = none */    public int $active = -1;    public bool $shuffle = false;    /**     * @var list<array{0: int, 1: string}> the lines played before (line, its song), the last one at the end: Précédent     * with Hasard goes back to them; remove() and move() keep their lines right, the song checks it     */    private array $history = [];    private const HISTORY = 500;    /** @var \Closure(int): int random number generator (tests give their own) */    private \Closure $random;    /** @param list<string> $items */    public function __construct(array $items = [])    {        $this->items = $items;        $this->random = static fn (int $max): int => random_int(0, max(0, $max));        $this->active = $items === [] ? -1 : 0;    }    /** @param \Closure(int): int $random returns 0..$max */    public function setRandom(\Closure $random): void    {        $this->random = $random;    }    public function count(): int    {        return count($this->items);    }    public function current(): ?string    {        return $this->items[$this->active] ?? null;    }    public function add(string $file): void    {        $this->items[] = $file;        if ($this->active < 0) {            $this->active = 0;        }    }    /** @param list<string> $files */    public function addAll(array $files): void    {        foreach ($files as $file) {            $this->add($file);        }    }    /** Removes lines (the edit mode's delete); the line playing keeps playing when it stays. @param list<int> $indexes */    public function remove(array $indexes): void    {        $playing = $this->current();        // a set of the lines to remove: one look-up per line (Ctrl+A then Suppr on thousands of songs stays instant)        $gone = [];        foreach ($indexes as $i) {            if (isset($this->items[$i])) {                $gone[$i] = true;            }        }        if ($gone === []) {            return;        }        $keep = [];        foreach ($this->items as $i => $file) {            if (!isset($gone[$i])) {                $keep[] = $file;            }        }        $removedBefore = 0;        foreach ($gone as $i => $_) {            $removedBefore += $i < $this->active ? 1 : 0;        }        // the lines played before: those removed go, the others move up by the lines removed above them        if ($this->history !== []) {            $shift = [];            $n = 0;            foreach ($this->items as $i => $_) {                $shift[$i] = $n;                $n += isset($gone[$i]) ? 1 : 0;            }            $history = [];            foreach ($this->history as [$line, $file]) {                if (!isset($gone[$line]) && isset($shift[$line])) {                    $history[] = [$line - $shift[$line], $file];                }            }            $this->history = $history;        }        $this->items = $keep;        if ($keep === []) {            $this->active = -1;        } elseif ($playing !== null && isset($gone[$this->active])) {            $this->active = min($this->active - $removedBefore, count($keep) - 1);        } else {            $this->active = max(0, $this->active - $removedBefore);        }    }    /** The line $from goes to the place $to (the others make room); the active line follows its song. */    public function move(int $from, int $to): void    {        $n = count($this->items);        if ($from === $to || $from < 0 || $to < 0 || $from >= $n || $to >= $n) {            return;        }        $item = array_splice($this->items, $from, 1);        array_splice($this->items, $to, 0, $item);        foreach ($this->history as $k => [$line]) {            $this->history[$k][0] = self::moved($line, $from, $to);        }        if ($this->active === $from) {            $this->active = $to;        } elseif ($from < $this->active && $to >= $this->active) {            $this->active--;        } elseif ($from > $this->active && $to <= $this->active) {            $this->active++;        }    }    /** Where a line goes when the line $from moves to $to. */    private static function moved(int $line, int $from, int $to): int    {        if ($line === $from) {            return $to;        }        if ($from < $line && $to >= $line) {            return $line - 1;        }        if ($from > $line && $to <= $line) {            return $line + 1;        }        return $line;    }    public function clear(): void    {        $this->items = [];        $this->active = -1;        $this->history = [];    }    /** The line playing goes into the history (before another one plays). */    private function remember(): void    {        if (isset($this->items[$this->active])) {            $this->history[] = [$this->active, $this->items[$this->active]];            if (count($this->history) > self::HISTORY) {                array_shift($this->history);            }        }    }    /** Hasard: any line but the one playing (with more than one line: the same song never comes twice in a row). */    private function randomLine(): int    {        $n = count($this->items);        if ($n <= 1 || $this->active < 0 || $this->active >= $n) {            return max(0, min($n - 1, ($this->random)($n - 1)));        }        $line = max(0, min($n - 2, ($this->random)($n - 2)));        return $line >= $this->active ? $line + 1 : $line;    }    /** The lines played before, the last one at the end. @return list<int> */    public function history(): array    {        return array_map(fn (array $h) => $h[0], $this->history);    }    /**     * Command3_Click: the next line (the first after the last one), or any line with Hasard. $accept: only the lines it     * says yes to (the play mode "only songs with lyrics"); none: null and nothing changes.     * @param (\Closure(string): bool)|null $accept     */    public function next(?\Closure $accept = null): ?string    {        if ($this->items === []) {            return null;        }        if ($accept !== null) {            $line = $this->acceptedLine($accept, 1);            if ($line === null) {                return null;            }            $this->remember();            $this->active = $line;            return $this->current();        }        $this->remember();        if ($this->shuffle) {            $this->active = $this->randomLine();        } else {            $this->active = $this->active >= count($this->items) - 1 ? 0 : $this->active + 1;        }        return $this->current();    }    /**     * Command2_Click: the line before (the last one before the first), or any line with Hasard. $accept: as next().     * @param (\Closure(string): bool)|null $accept     */    public function previous(?\Closure $accept = null): ?string    {        if ($this->items === []) {            return null;        }        if ($this->shuffle) {            // Hasard: back to the song really played before (its line, or where its song went), else any other line            while (($last = array_pop($this->history)) !== null) {                [$line, $file] = $last;                if (($this->items[$line] ?? null) !== $file) {                    $found = array_search($file, $this->items, true);                    $line = is_int($found) ? $found : -1;                }                if ($line >= 0 && $line !== $this->active && ($accept === null || $accept($this->items[$line]))) {                    $this->active = $line;                    return $this->current();                }            }        }        if ($accept !== null) {            $line = $this->acceptedLine($accept, -1);            if ($line === null) {                return null;            }            $this->active = $line;            return $this->current();        }        if ($this->shuffle) {            $this->active = $this->randomLine();        } else {            $this->active = $this->active <= 0 ? count($this->items) - 1 : $this->active - 1;        }        return $this->current();    }    /**     * The line to go to among those $accept says yes to: the next one going $step (round the list), or with Hasard any     * of them but the one playing (the one playing when it is the only one). null: none.     * @param \Closure(string): bool $accept     */    private function acceptedLine(\Closure $accept, int $step): ?int    {        $n = count($this->items);        if ($this->shuffle) {            $lines = [];            foreach ($this->items as $i => $file) {                if ($i !== $this->active && $accept($file)) {                    $lines[] = $i;                }            }            if ($lines === []) {                return isset($this->items[$this->active]) && $accept($this->items[$this->active]) ? $this->active : null;            }            return $lines[max(0, min(count($lines) - 1, ($this->random)(count($lines) - 1)))];        }        $start = $this->active < 0 ? ($step > 0 ? -1 : 0) : $this->active;        for ($k = 1; $k <= $n; $k++) {            $line = (($start + $step * $k) % $n + $n) % $n;            if ($accept($this->items[$line])) {                return $line;            }        }        return null;    }    public function select(int $index): ?string    {        if (!isset($this->items[$index])) {            return null;        }        if ($index !== $this->active) {            $this->remember();     // a line clicked: Précédent with Hasard comes back to the song before it        }        $this->active = $index;        return $this->current();    }    /** The icon of a line: mp3 (also ogg, flac), wav, mid, or cd for anything else (indice2 / 22 / 23 / 24 of Form2). */    public static function kind(string $file): string    {        return match (Text::extension($file)) {            'mp3', 'ogg', 'flac', 'mp2' => 'mp3',            'wav' => 'wav',            'mid', 'midi' => 'mid',            'mp4', 'webm', 'mkv' => 'vid',            default => 'cd',        };    }    public static function isMedia(string $file): bool    {        return in_array(Text::extension($file), self::AUDIO, true) || self::isVideo($file);    }    public static function isVideo(string $file): bool    {        return in_array(Text::extension($file), self::VIDEO, true);    }    // .FLS: "[FLS]" then one file per line (written by VB's Write #1, so between quotes) -------------------------    public function toFls(): string    {        $out = "\"[FLS]\"\r\n";        foreach ($this->items as $file) {            $out .= '"' . Text::toCp1252($file) . "\"\r\n";        }        return $out;    }    /** @return list<string>|null the files of a .FLS, null when it is not one */    public static function parseFls(string $content): ?array    {        $lines = Text::lines($content);        if ($lines === [] || strtoupper(Text::unquote($lines[0])) !== '[FLS]') {            return null;        }        $files = [];        foreach (array_slice($lines, 1) as $line) {            $file = Text::unquote($line);            if ($file !== '') {                $files[] = $file;            }        }        return $files;    }}