'ogg', 'ID3' => 'mp3', ]; public function __construct(private readonly string $dir) { if (!is_dir($this->dir) && !mkdir($this->dir, 0775, true) && !is_dir($this->dir)) { throw new RuntimeException("Cannot create sound directory {$this->dir}"); } } /** A stored file name, as it appears in a project document. */ public static function isValidName(string $name): bool { return (bool) preg_match('/^[a-f0-9]{64}\.(mp3|ogg|wav|m4a)$/', $name); } /** * Stores the raw bytes of a sound and returns its record. * * The format is read from the file's own signature, never from anything the client says – * browsers report a dropped `.m4a` as `audio/mp4`, `audio/x-m4a` or nothing at all, and an * `.ogg` as either `audio/ogg` or `video/ogg`. * * `$originalName` is kept beside the file as a caption (see OriginalName): the hash says * nothing, and there is no tag in here that is worth trusting for a label. * * @return array{file:string,name:string,bytes:int} * @throws InvalidSoundException when the bytes are not a supported sound */ public function store(string $bytes, string $originalName = ''): array { $extension = self::extensionOf($bytes); if ($extension === '') { throw new InvalidSoundException('Not a sound file – use MP3, OGG, WAV or M4A'); } $file = hash('sha256', $bytes) . '.' . $extension; $path = $this->dir . '/' . $file; if (!is_file($path)) { $this->writeFile($path, $bytes); } OriginalName::write($this->dir, $file, $originalName); return ['file' => $file, 'name' => OriginalName::read($this->dir, $file), 'bytes' => strlen($bytes)]; } /** * Every stored file, newest first – what the sound picker offers. A sound has nothing to show, * so the picker plays it instead; length is not read here, since only a decoder knows it. * * @return list */ public function list(): array { $items = []; foreach (glob($this->dir . '/*.*') ?: [] as $path) { $file = basename($path); // Sidecars share the directory and are skipped: `{hash}.mp3.json` is not a valid name. if (!self::isValidName($file)) { continue; } $items[] = [ 'file' => $file, 'name' => OriginalName::read($this->dir, $file), 'bytes' => (int) filesize($path), 'updatedAt' => gmdate('c', (int) filemtime($path)), ]; } usort($items, static fn(array $a, array $b): int => strcmp($b['updatedAt'], $a['updatedAt'])); return $items; } public function delete(string $file): bool { if (!self::isValidName($file)) { return false; } $path = $this->dir . '/' . $file; if (!is_file($path) || !unlink($path)) { return false; } OriginalName::delete($this->dir, $file); return true; } /** The format these bytes are, `''` when they are none we take. */ private static function extensionOf(string $bytes): string { // The shortest thing that can still carry a header of any of the four formats. if (strlen($bytes) < 12) { return ''; } foreach (self::SIGNATURES as $magic => $extension) { if (str_starts_with($bytes, $magic)) { return $extension; } } // Both are RIFF/ISO container formats, so the type sits past the size field, not at byte 0. if (str_starts_with($bytes, 'RIFF') && substr($bytes, 8, 4) === 'WAVE') { return 'wav'; } if (substr($bytes, 4, 4) === 'ftyp') { return 'm4a'; } return self::mp3Extension($bytes); } /** * A tagless MP3: a frame header is eleven set bits (`0xFF 0xEx`/`0xFx`), and the two bits below * them name the MPEG version, of which `01` is reserved – demanding that much keeps a random * binary that happens to start with `0xFF` out. */ private static function mp3Extension(string $bytes): string { $first = ord($bytes[0]); $second = ord($bytes[1]); $version = ($second >> 3) & 0b11; return $first === 0xFF && ($second & 0xE0) === 0xE0 && $version !== 0b01 ? 'mp3' : ''; } /** Temp file plus rename, so a reader never sees a half-written sound (see TextureStore). */ private function writeFile(string $path, string $bytes): void { $tmp = $path . '.' . bin2hex(random_bytes(4)) . '.tmp'; if (file_put_contents($tmp, $bytes, LOCK_EX) === false || !rename($tmp, $path)) { @unlink($tmp); throw new RuntimeException('Cannot write sound file'); } @chmod($path, 0664); } } /** Thrown by SoundStore::store when the uploaded bytes are not a usable sound. */ final class InvalidSoundException extends RuntimeException { }