PL
apps/winzik / src / Model / Id3Tag.php · commit 6576d6f
<?phpnamespace App\Model;/** * The ID3v1 tag of an MP3 file: the last 128 bytes, "TAG" + title (30) + artist (30) + album (30) + year (4) + * comment (30) + genre (1 byte). The same offsets as GetTitre / PutTitre... of WinZik 2001 (winster.bas): * FileLen - 124 for the title, - 94 the artist, - 64 the album, - 34 the year, - 30 the comment, the last byte the genre. */final class Id3Tag{    /** The 80 genres of ID3v1 (GenreConv of winster.bas, in its order). */    public const GENRES = [        'Blues', 'Classic Rock', 'Country', 'Dance', 'Disco', 'Funk', 'Grunge', 'Hip-Hop', 'Jazz', 'Metal',        'New Age', 'Oldies', 'Other', 'Pop', 'R&B', 'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial',        'Alternative', 'Ska', 'Death Metal', 'Pranks', 'Soundtrack', 'Euro-Techno', 'Ambient', 'Trip-Hop', 'Vocal', 'Jazz+Funk',        'Fusion', 'Trance', 'Classical', 'Instrumental', 'Acid', 'House', 'Game', 'Sound Clip', 'Gospel', 'Noise',        'AlternRock', 'Bass', 'Soul', 'Punk', 'Space', 'Meditative', 'Instrumental Pop', 'Instrumental Rock', 'Ethnic', 'Gothic',        'Darkwave', 'Techno-Industrial', 'Electronic', 'Pop-Folk', 'Eurodance', 'Dream', 'Southern Rock', 'Comedy', 'Cult', 'Gangsta',        'Top 40', 'Christian Rap', 'Pop/Funk', 'Jungle', 'Native American', 'Cabaret', 'New Wave', 'Psychadelic', 'Rave', 'Showtunes',        'Trailer', 'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz', 'Polka', 'Retro', 'Musical', 'Rock & Roll', 'Hard Rock',    ];    /** "Other": what an unknown genre byte becomes (If sngG > 79 Then sngG = 12) */    public const OTHER = 12;    public function __construct(        public string $title = '',        public string $artist = '',        public string $album = '',        public string $year = '',        public string $comment = '',        public int $genre = self::OTHER,        /** false: the file has no tag (yet) */        public bool $present = false,    ) {    }    /** ID3v2: the comment as it is (yt-dlp: the address), when a longer text (the description) was taken as the comment */    public string $commentRaw = '';    /** WinZik's own marks (ID3v2 TXXX WINZIK_START / WINZIK_END): where the song really begins / ends, null: none */    public ?float $markStart = null;    public ?float $markEnd = null;    /** ID3v2 APIC: the picture of the album (its bytes, '' when none) */    public string $picture = '';    public static function read(string $file): self    {        $size = is_file($file) ? (int)@filesize($file) : 0;        if ($size < 128) {            return new self();        }        $f = @fopen($file, 'rb');        if ($f === false) {            return new self();        }        $head = (string)fread($f, 10);        $v2 = null;        if (strlen($head) === 10 && substr($head, 0, 3) === 'ID3') {            // ID3v2 at the start (what yt-dlp / ffmpeg write: long titles, a long comment)            $len = self::syncsafe(substr($head, 6, 4));            $v2 = self::parseV2(ord($head[3]), ord($head[5]), (string)fread($f, min($len, 2 * 1024 * 1024)));        }        fseek($f, $size - 128);        $raw = (string)fread($f, 128);        fclose($f);        $tag = self::parse($raw);        if ($v2 !== null) {            // ID3v2 completes ID3v1 where it is empty or only the beginning of it (30 characters): what WinZik wrote in ID3v1            // (the tag window) stays            foreach (['title', 'artist', 'album', 'year', 'comment'] as $field) {                $v1 = $tag->{$field};                $long = $v2->{$field};                $sources = $field === 'comment' ? [$long, $v2->commentRaw] : [$long];                $cut = false;                foreach ($sources as $src) {                    $cut = $cut || ($src !== '' && strlen($v1) >= 26 && str_starts_with($src, $v1));     // 30 bytes, its end cut                }                if ($long !== '' && ($v1 === '' || $cut)) {                    $tag->{$field} = $long;                }            }            if ($v2->genre !== self::OTHER || !$tag->present) {                $tag->genre = $v2->genre;            }            $tag->present = true;            $tag->picture = $v2->picture;            [$tag->markStart, $tag->markEnd] = [$v2->markStart, $v2->markEnd];        }        return $tag;    }    private static function syncsafe(string $b): int    {        return strlen($b) < 4 ? 0 : ((ord($b[0]) & 0x7f) << 21) | ((ord($b[1]) & 0x7f) << 14) | ((ord($b[2]) & 0x7f) << 7) | (ord($b[3]) & 0x7f);    }    /** The frames of an ID3v2.2 / 2.3 / 2.4 tag (its body, after the 10 bytes of its header). */    public static function parseV2(int $major, int $flags, string $body): self    {        $tag = new self();        if ($flags & 0x80 && $major < 4) {            $body = str_replace("\xFF\x00", "\xFF", $body);     // unsynchronisation of the whole tag (2.3)        }        if ($flags & 0x40 && $major >= 3 && strlen($body) > 4) {            // an extended header: skipped            $ext = $major === 4 ? self::syncsafe(substr($body, 0, 4)) : (int)unpack('N', substr($body, 0, 4))[1] + 4;            $body = substr($body, $ext);        }        $names = $major === 2            ? ['TT2' => 'title', 'TP1' => 'artist', 'TAL' => 'album', 'TYE' => 'year', 'COM' => 'comment', 'TCO' => 'genre']            : ['TIT2' => 'title', 'TPE1' => 'artist', 'TALB' => 'album', 'TYER' => 'year', 'TDRC' => 'year', 'COMM' => 'comment', 'TCON' => 'genre'];        $idLen = $major === 2 ? 3 : 4;        $described = null;        $headLen = $major === 2 ? 6 : 10;        for ($i = 0; $i + $headLen <= strlen($body);) {            $id = substr($body, $i, $idLen);            if (!preg_match('/^[A-Z0-9]+$/', $id)) {                break;      // the padding            }            $size = match ($major) {                2 => (ord($body[$i + 3]) << 16) | (ord($body[$i + 4]) << 8) | ord($body[$i + 5]),                4 => self::syncsafe(substr($body, $i + 4, 4)),                default => (int)unpack('N', substr($body, $i + 4, 4))[1],            };            $data = substr($body, $i + $headLen, $size);            $i += $headLen + $size;            if (($id === 'APIC' || $id === 'PIC') && $data !== '' && $tag->picture === '') {                // the cover: encoding, a type (APIC: "image/jpeg"\0, PIC: 3 letters), a kind byte, a description, the picture                $enc = ord($data[0]);                $at = $id === 'APIC' ? (int)strpos($data, "\0", 1) + 1 : 4;                $at++;      // the kind of picture                $rest = substr($data, $at);                $end = $enc === 1 || $enc === 2 ? self::endUtf16($rest) : strpos($rest, "\0");                if ($end !== false) {                    $tag->picture = substr($rest, $end + ($enc === 1 || $enc === 2 ? 2 : 1));                }                continue;            }            if (($id === 'TXXX' || $id === 'TXX') && $data !== '') {                // ffmpeg / yt-dlp: TXXX "description" (the video's text) and "comment" (its address)                $enc = ord($data[0]);                $rest = substr($data, 1);                $end = $enc === 1 || $enc === 2 ? self::endUtf16($rest) : strpos($rest, "\0");                if ($end !== false) {                    $key = strtolower(self::decode($enc, substr($rest, 0, $end)));                    $value = trim(self::decode($enc, substr($rest, $end + ($enc === 1 || $enc === 2 ? 2 : 1))));                    if ($key === 'winzik_start' && is_numeric($value)) {                        $tag->markStart = (float)$value;                    } elseif ($key === 'winzik_end' && is_numeric($value)) {                        $tag->markEnd = (float)$value;                    } elseif ($key === 'description' && $value !== '') {                        $described = $value;                    } elseif ($key === 'comment' && $tag->comment === '') {                        $tag->comment = $value;                        $tag->commentRaw = $value;                    }                }                continue;            }            $field = $names[$id] ?? null;            if ($field === null || $data === '') {                continue;            }            $enc = ord($data[0]);            if ($field === 'comment') {                // encoding, language (3), a short description ended by a 0, then the text                $rest = substr($data, 4);                $end = $enc === 1 || $enc === 2 ? self::endUtf16($rest) : strpos($rest, "\0");                $value = self::decode($enc, $end === false ? '' : substr($rest, $end + ($enc === 1 || $enc === 2 ? 2 : 1)));            } else {                $value = self::decode($enc, substr($data, 1));            }            $value = trim(str_replace("\0", ' ', $value));            if ($field === 'genre') {                // "(17)", "17" or "(17)Rock": the number (past the 80 of WinZik: Other), else the name                $tag->genre = preg_match('/^\(?(\d+)\)?/', $value, $m) ? ((int)$m[1] > 79 ? self::OTHER : (int)$m[1]) : self::genreIndex($value);            } elseif ($field === 'year') {                $tag->year = substr($value, 0, 4);            } elseif ($tag->{$field} === '') {                $tag->{$field} = $value;            }        }        if ($described !== null) {            $tag->commentRaw = $tag->commentRaw !== '' ? $tag->commentRaw : $tag->comment;            $tag->comment = $described;     // the text of the video says more than its address        }        return $tag;    }    /** Where the first UTF-16 0 (two zero bytes, on a character boundary) is. */    private static function endUtf16(string $s): int|false    {        for ($i = 0; $i + 1 < strlen($s); $i += 2) {            if ($s[$i] === "\0" && $s[$i + 1] === "\0") {                return $i;            }        }        return false;    }    private static function decode(int $enc, string $raw): string    {        $raw = rtrim($raw, "\0");        return match ($enc) {            1 => (string)mb_convert_encoding($raw, 'UTF-8', str_starts_with($raw, "\xFF\xFE") || str_starts_with($raw, "\xFE\xFF") ? 'UTF-16' : 'UTF-16LE'),            2 => (string)mb_convert_encoding($raw, 'UTF-8', 'UTF-16BE'),            3 => $raw,            default => (string)mb_convert_encoding($raw, 'UTF-8', 'ISO-8859-1'),        };    }    /** The tag of the last 128 bytes of a file. */    public static function parse(string $raw): self    {        if (strlen($raw) !== 128 || substr($raw, 0, 3) !== 'TAG') {            return new self();        }        $genre = ord($raw[127]);        return new self(            self::text(substr($raw, 3, 30)),            self::text(substr($raw, 33, 30)),            self::text(substr($raw, 63, 30)),            self::text(substr($raw, 93, 4)),            self::text(substr($raw, 97, 30)),            $genre > 79 ? self::OTHER : $genre,            true,        );    }    /** The 128 bytes of this tag. */    public function bytes(): string    {        return 'TAG' . self::field($this->title, 30) . self::field($this->artist, 30) . self::field($this->album, 30)            . self::field($this->year, 4) . self::field($this->comment, 30) . chr(max(0, min(255, $this->genre)));    }    /**     * Writes the tag into the file: replaces the old one, or adds it at the end (CheckTag of 2001 did the same).     * @return bool false when the file is read-only or missing     */    /**     * WinZik's marks written into the MP3's ID3v2 tag (TXXX WINZIK_START / WINZIK_END; null: removed), its other frames     * kept as they are. A tag WinZik cannot rewrite safely (unsynchronised, extended header, v2.2): false (the marks then     * live in var/marks.json only).     */    public static function writeMarks(string $file, ?float $start, ?float $end): bool    {        $data = is_file($file) && is_writable($file) ? @file_get_contents($file) : false;        if ($data === false) {            return false;        }        $major = 3;        $frames = '';        $audio = $data;        if (substr($data, 0, 3) === 'ID3' && strlen($data) >= 10) {            $major = ord($data[3]);            $flags = ord($data[5]);            if ($major < 3 || $major > 4 || ($flags & 0xC0) !== 0) {                return false;            }            $len = self::syncsafe(substr($data, 6, 4));            $body = substr($data, 10, $len);            $audio = (string)substr($data, 10 + $len + (($flags & 0x10) !== 0 ? 10 : 0));            for ($i = 0; $i + 10 <= strlen($body);) {                $id = substr($body, $i, 4);                if (!preg_match('/^[A-Z0-9]{4}$/', $id)) {                    break;      // the padding                }                $size = $major === 4 ? self::syncsafe(substr($body, $i + 4, 4)) : (int)unpack('N', substr($body, $i + 4, 4))[1];                $frame = substr($body, $i, 10 + $size);                $i += 10 + $size;                if ($id === 'TXXX' && preg_match('/^.WINZIK_(START|END)\0/s', substr($frame, 10, 20))) {                    continue;   // ours, written again below                }                $frames .= $frame;            }        }        foreach (['WINZIK_START' => $start, 'WINZIK_END' => $end] as $name => $value) {            if ($value === null) {                continue;            }            $payload = "\0" . $name . "\0" . rtrim(rtrim(sprintf('%.3F', $value), '0'), '.');            $size = strlen($payload);            $frames .= 'TXXX' . ($major === 4 ? self::toSyncsafe($size) : pack('N', $size)) . "\0\0" . $payload;        }        $padding = str_repeat("\0", 512);        $tag = 'ID3' . chr($major) . "\0\0" . self::toSyncsafe(strlen($frames) + strlen($padding)) . $frames . $padding;        $tmp = $file . '.winzik-tmp';        if (@file_put_contents($tmp, $tag . $audio) === false || !@rename($tmp, $file)) {            @unlink($tmp);            return false;        }        clearstatcache(true, $file);        return true;    }    private static function toSyncsafe(int $n): string    {        return chr(($n >> 21) & 0x7F) . chr(($n >> 14) & 0x7F) . chr(($n >> 7) & 0x7F) . chr($n & 0x7F);    }    public function write(string $file): bool    {        if (!is_file($file) || !is_writable($file)) {            return false;        }        $size = (int)filesize($file);        $f = @fopen($file, 'r+b');        if ($f === false) {            return false;        }        $hasTag = false;        if ($size >= 128) {            fseek($f, $size - 128);            $hasTag = fread($f, 3) === 'TAG';        }        fseek($f, $hasTag ? $size - 128 : $size);        $ok = fwrite($f, $this->bytes()) === 128;        fclose($f);        clearstatcache(true, $file);        $this->present = $ok;        return $ok;    }    public function genreName(): string    {        return self::GENRES[$this->genre] ?? 'Other';    }    public static function genreIndex(string $name): int    {        $i = array_search($name, self::GENRES, true);        return $i === false ? self::OTHER : (int)$i;    }    /** The combo box lines of 2001: "00 Blues", "01 Classic Rock"... */    public static function genreItems(): array    {        $items = [];        foreach (self::GENRES as $i => $name) {            $items[] = sprintf('%02d %s', $i, $name);        }        return $items;    }    /** ID3v1 is Latin-1 (Windows 1252 in 2001): to UTF-8, padding removed. */    private static function text(string $bytes): string    {        $raw = rtrim(explode("\0", $bytes, 2)[0], " \0");        if (preg_match('/[\x80-\xff]/', $raw) && preg_match('//u', $raw) === 1) {            return $raw;        }        // ffmpeg / yt-dlp write ID3v1 in UTF-8, cut at 30 bytes (sometimes in the middle of a letter): the cut letter goes.        // Only a full field can be cut there, at a lead byte followed by fewer continuation bytes than it announces. A lone        // byte of à..ÿ alone after plain letters is the Latin-1 of 2001 ("Café", "Été"), not half of a UTF-8 letter.        if (strlen($raw) === strlen($bytes) && preg_match('/([\xC2-\xF4])([\x80-\xBF]*)$/', $raw, $m)) {            $lead = ord($m[1]);            $needs = $lead >= 0xF0 ? 3 : ($lead >= 0xE0 ? 2 : 1);            $try = substr($raw, 0, -strlen($m[0]));            $utf8Before = preg_match('/[\x80-\xff]/', $try) === 1;            $latin1Letter = !$utf8Before && $m[2] === '' && $lead >= 0xE0;            if (strlen($m[2]) < $needs && !$latin1Letter && preg_match('//u', $try) === 1) {                return $try;            }        }        return Text::toUtf8($raw);    }    private static function field(string $text, int $length): string    {        return str_pad(substr(Text::toCp1252($text), 0, $length), $length, "\0");    }}