IT
apps/winzik / src / Work / Worker.php · commit 6576d6f
<?phpnamespace App\Work;use App\Model\AudioInfo;use App\Model\Id3Tag;/** * A helper process of WinZik (WorkerPool, bin/winzik-worker.php): jobs as JSON lines on its stdin, an answer per line on its * stdout; its first line says it is ready. What would make the interface wait is done here, on another core: * *   {"id": 1, "type": "describe", "path": "/abs/song.mp3", "covers": "/abs/cache/covers"} *        -> {tag: {...}, info: {...}}: its ID3 tag and its length (a whole MP3 read through); its cover goes to the cache *   {"id": 2, "type": "ping"} -> "pong" */final class Worker{    /** @param resource $in @param resource $out */    public static function serve($in, $out): int    {        @ini_set('memory_limit', '512M');        if (function_exists('proc_nice')) {            @proc_nice(5);      // below the interface: on a busy computer the player stays smooth        }        @ini_set('display_errors', 'stderr');        fwrite($out, json_encode(['ready' => true, 'pid' => getmypid()]) . "\n");        fflush($out);        while (($line = fgets($in)) !== false) {            $job = json_decode($line, true);            if (!is_array($job) || !isset($job['id'])) {                continue;            }            if (($job['type'] ?? '') === 'exit') {                break;            }            try {                $answer = ['id' => $job['id'], 'ok' => true, 'value' => self::run($job)];            } catch (\Throwable $e) {                $answer = ['id' => $job['id'], 'ok' => false, 'error' => $e->getMessage(), 'class' => $e::class, 'at' => basename($e->getFile()) . ':' . $e->getLine()];            }            $json = json_encode($answer, JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PRESERVE_ZERO_FRACTION);            fwrite($out, ($json === false ? json_encode(['id' => $job['id'], 'ok' => false, 'error' => json_last_error_msg()]) : $json) . "\n");            fflush($out);        }        return 0;    }    /** @param array<string, mixed> $job */    public static function run(array $job): mixed    {        switch ((string)($job['type'] ?? '')) {            case 'ping':                return 'pong';            case 'blanks':                // the silence at the start and the end of a song (its WAV): where it really begins and ends                [$start, $end] = \App\Media\Blanks::find((string)($job['wav'] ?? ''));                return ['start' => $start, 'end' => $end];            case 'describe':                return self::describe((string)($job['path'] ?? ''), (string)($job['covers'] ?? ''));        }        throw new \InvalidArgumentException('unknown job ' . (string)($job['type'] ?? ''));    }    /** @return array{tag: array<string, mixed>, info: array<string, mixed>} */    public static function describe(string $path, string $covers): array    {        $tag = strtolower(pathinfo($path, PATHINFO_EXTENSION)) === 'mp3' ? Id3Tag::read($path) : new Id3Tag();        $info = AudioInfo::of($path);        if ($tag->picture !== '' && $covers !== '') {            // the cover in the cache (App\Media\Covers reads it there): the picture itself does not travel back            $key = $covers . '/' . md5($path);            if (!is_file("$key.jpg") && !is_file("$key.png")) {                @mkdir($covers, 0777, true);                @file_put_contents($key . (str_starts_with($tag->picture, "\x89PNG") ? '.png' : '.jpg'), $tag->picture);            }        }        return ['tag' => self::tagArray($tag), 'info' => ['duration' => $info->duration, 'kbps' => $info->kbps, 'sampleRate' => $info->sampleRate, 'channels' => $info->channels]];    }    /** @return array<string, mixed> */    public static function tagArray(Id3Tag $tag): array    {        return ['title' => $tag->title, 'artist' => $tag->artist, 'album' => $tag->album, 'year' => $tag->year, 'comment' => $tag->comment,            'genre' => $tag->genre, 'present' => $tag->present, 'commentRaw' => $tag->commentRaw];    }    /** @param array<string, mixed> $a */    public static function tagFrom(array $a): Id3Tag    {        $tag = new Id3Tag((string)($a['title'] ?? ''), (string)($a['artist'] ?? ''), (string)($a['album'] ?? ''), (string)($a['year'] ?? ''),            (string)($a['comment'] ?? ''), (int)($a['genre'] ?? Id3Tag::OTHER), (bool)($a['present'] ?? false));        $tag->commentRaw = (string)($a['commentRaw'] ?? '');        return $tag;    }}