Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
132 / 132
100.00% covered (success)
100.00%
12 / 12
CRAP
100.00% covered (success)
100.00%
1 / 1
MidiFileFaker
100.00% covered (success)
100.00%
132 / 132
100.00% covered (success)
100.00%
12 / 12
55
100.00% covered (success)
100.00%
1 / 1
 createOriginalFilename
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createMimeType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isSupported
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createResource
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createMidi
100.00% covered (success)
100.00%
57 / 57
100.00% covered (success)
100.00%
1 / 1
10
 createMelodyBars
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
9
 toNote
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 addChord
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
7
 addDrums
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
17
 addNote
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 encodeTrack
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 variableLength
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2namespace Apie\Faker\FileFakers;
3
4use Apie\Faker\Interfaces\ApieAudioFileFaker;
5use Faker\Generator;
6use Nyholm\Psr7\Stream;
7
8/**
9 * Generates a small song as standard midi file (format 1) with 3 tracks: melody, chords and drums.
10 *
11 * Song structure: intro, chorus, verse, chorus, verse, outro. A bridge is inserted once at a random position.
12 */
13final class MidiFileFaker implements ApieAudioFileFaker
14{
15    private const TICKS_PER_QUARTER = 480;
16    private const BAR_TICKS = self::TICKS_PER_QUARTER * 4;
17    private const EIGHTH = self::TICKS_PER_QUARTER / 2;
18
19    private const MAJOR = [0, 2, 4, 5, 7, 9, 11];
20    private const MINOR = [0, 2, 3, 5, 7, 8, 10];
21
22    private const PROGRESSIONS = [
23        [0, 4, 5, 3],
24        [0, 3, 4, 3],
25        [0, 5, 3, 4],
26        [5, 3, 0, 4],
27        [0, 2, 3, 4],
28        [1, 4, 0, 5],
29    ];
30
31    private const KICK = 36;
32    private const SNARE = 38;
33    private const HIHAT = 42;
34    private const OPEN_HIHAT = 46;
35    private const CRASH = 49;
36
37    public function createOriginalFilename(Generator $faker): string
38    {
39        return $faker->word() . '.mid';
40    }
41
42    public function createMimeType(): string
43    {
44        return 'audio/midi';
45    }
46
47    public static function isSupported(): bool
48    {
49        return true;
50    }
51
52    /** @return resource */
53    public function createResource(Generator $faker, string $originalFilename, string $mimeType): mixed
54    {
55        return Stream::create($this->createMidi($faker))->detach();
56    }
57
58    private function createMidi(Generator $faker): string
59    {
60        $scale = $faker->boolean() ? self::MAJOR : self::MINOR;
61        $root = $faker->numberBetween(0, 11);
62        $tempo = $faker->numberBetween(80, 150);
63
64        $progressions = [
65            'chorus' => $faker->randomElement(self::PROGRESSIONS),
66            'verse' => $faker->randomElement(self::PROGRESSIONS),
67            'bridge' => $faker->randomElement(self::PROGRESSIONS),
68        ];
69        $progressions['intro'] = $progressions['verse'];
70        $progressions['outro'] = $progressions['chorus'];
71
72        $sections = [
73            ['intro', 2],
74            ['chorus', 4],
75            ['verse', 4],
76            ['chorus', 4],
77            ['verse', 4],
78            ['outro', 2],
79        ];
80        // bridge goes after either verse, so it always leads into a chorus or the outro.
81        array_splice($sections, $faker->randomElement([3, 5]), 0, [['bridge', 4]]);
82
83        $melodies = [];
84        $melody = [];
85        $chords = [];
86        $drums = [];
87        $tick = 0;
88        foreach ($sections as [$type, $bars]) {
89            $progression = $progressions[$type];
90            $melodyKey = in_array($type, ['intro', 'outro'], true) ? ($type === 'intro' ? 'verse' : 'chorus') : $type;
91            $melodies[$melodyKey] ??= $this->createMelodyBars($faker, $progressions[$melodyKey], $melodyKey);
92            for ($bar = 0; $bar < $bars; $bar++) {
93                $chordDegree = $progression[$bar % 4];
94                $barStart = $tick + $bar * self::BAR_TICKS;
95                $isLastBar = $bar === $bars - 1;
96                if ($type !== 'intro' || $bar > 0) {
97                    foreach ($melodies[$melodyKey][$bar % 4] as [$slot, $length, $offset]) {
98                        $degree = $chordDegree + $offset;
99                        $this->addNote(
100                            $melody,
101                            $barStart + $slot * self::EIGHTH,
102                            $length * self::EIGHTH,
103                            $this->toNote($scale, $root, $degree, 72),
104                            $type === 'chorus' ? 100 : 85,
105                            0
106                        );
107                    }
108                }
109                $this->addChord($chords, $barStart, $scale, $root, $chordDegree, $type);
110                $this->addDrums($drums, $barStart, $type, $bar === 0, $isLastBar);
111            }
112            $tick += $bars * self::BAR_TICKS;
113        }
114
115        $tempoTrack = [
116            [0, 0, "\xFF\x51\x03" . substr(pack('N', intdiv(60_000_000, $tempo)), 1)],
117            [0, 0, "\xFF\x58\x04\x04\x02\x18\x08"],
118        ];
119        // Program changes: piano for the chords, synth lead for the melody.
120        $melody[] = [0, 0, "\xC0" . chr(80)];
121        $chords[] = [0, 0, "\xC1" . chr(0)];
122
123        $header = 'MThd' . pack('Nnnn', 6, 1, 3, self::TICKS_PER_QUARTER);
124
125        return $header
126            . $this->encodeTrack(array_merge($tempoTrack, $melody), $tick)
127            . $this->encodeTrack($chords, $tick)
128            . $this->encodeTrack($drums, $tick);
129    }
130
131    /**
132     * @param array<int, int> $progression
133     * @return array<int, array<int, array{int, int, int}>> per bar a list of [eighth slot, length in eighths, degree offset]
134     */
135    private function createMelodyBars(Generator $faker, array $progression, string $type): array
136    {
137        $bars = [];
138        $offset = 0;
139        $maxOffset = $type === 'chorus' ? 9 : 6;
140        foreach ($progression as $barIndex => $_) {
141            $notes = [];
142            $slot = 0;
143            while ($slot < 8) {
144                $length = min(8 - $slot, $faker->randomElement($type === 'chorus' ? [1, 2, 2, 4] : [2, 2, 4, 4]));
145                if ($slot > 0 && $faker->boolean(15)) {
146                    $slot += $length;
147                    continue;
148                }
149                // first note of a bar is a chord tone (0, 2 or 4 steps from the chord root), others move stepwise.
150                $offset = $slot === 0
151                    ? $faker->randomElement([0, 2, 4])
152                    : max(-2, min($maxOffset, $offset + $faker->randomElement([-2, -1, -1, 1, 1, 2])));
153                $notes[] = [$slot, $length, $offset];
154                $slot += $length;
155            }
156            // resolve to the root on the very last bar.
157            if ($barIndex === 3) {
158                $last = array_pop($notes);
159                $notes[] = [$last[0], $last[1], 0];
160            }
161            $bars[] = $notes;
162        }
163
164        return $bars;
165    }
166
167    /** @param array<int, int> $scale */
168    private function toNote(array $scale, int $root, int $degree, int $base): int
169    {
170        $octave = intdiv($degree, 7) - ($degree < 0 && $degree % 7 !== 0 ? 1 : 0);
171        $index = (($degree % 7) + 7) % 7;
172        return $base - 12 + $root + $scale[$index] + 12 * $octave;
173    }
174
175    /**
176     * @param array<int, array{int, int, string}> $events
177     * @param array<int, int> $scale
178     */
179    private function addChord(array &$events, int $barStart, array $scale, int $root, int $degree, string $type): void
180    {
181        $notes = [];
182        foreach ([0, 2, 4] as $step) {
183            $notes[] = $this->toNote($scale, $root, $degree + $step, 60);
184        }
185        $velocity = $type === 'chorus' ? 80 : 65;
186        if ($type === 'chorus') {
187            // chorus: repeated half-bar stabs
188            foreach ([0, self::BAR_TICKS / 2] as $offset) {
189                foreach ($notes as $note) {
190                    $this->addNote($events, $barStart + $offset, self::BAR_TICKS / 2 - 10, $note, $velocity, 1);
191                }
192            }
193            return;
194        }
195        foreach ($notes as $note) {
196            $this->addNote($events, $barStart, self::BAR_TICKS - 10, $note, $velocity, 1);
197        }
198    }
199
200    /** @param array<int, array{int, int, string}> $events */
201    private function addDrums(array &$events, int $barStart, string $type, bool $firstBar, bool $lastBar): void
202    {
203        $hit = function (int $slot, int $note, int $velocity) use (&$events, $barStart): void {
204            $this->addNote($events, $barStart + $slot * self::EIGHTH, self::EIGHTH - 10, $note, $velocity, 9);
205        };
206        if ($firstBar && $type !== 'intro') {
207            $hit(0, self::CRASH, 110);
208        }
209        // hi-hat
210        for ($slot = 0; $slot < 8; $slot++) {
211            if ($type === 'intro' || $type === 'outro' || $type === 'verse' || $type === 'chorus' || $slot % 2 === 0) {
212                $hit($slot, $type === 'chorus' && $slot === 7 ? self::OPEN_HIHAT : self::HIHAT, $slot % 2 === 0 ? 80 : 60);
213            }
214        }
215        if ($type === 'intro') {
216            return;
217        }
218        if ($type === 'bridge') {
219            // half-time feel
220            $hit(0, self::KICK, 100);
221            $hit(4, self::SNARE, 100);
222        } else {
223            $hit(0, self::KICK, 110);
224            $hit(4, self::KICK, 100);
225            $hit(2, self::SNARE, 100);
226            $hit(6, self::SNARE, 100);
227            if ($type === 'chorus') {
228                $hit(5, self::KICK, 90);
229            }
230        }
231        // small fill on the last bar before the next section
232        if ($lastBar && $type !== 'outro') {
233            $hit(7, self::SNARE, 110);
234        }
235    }
236
237    /** @param array<int, array{int, int, string}> $events */
238    private function addNote(array &$events, int $start, int $length, int $note, int $velocity, int $channel): void
239    {
240        $note = max(0, min(127, $note));
241        // order 1 for note off so off events at the same tick are sorted before note on events (order 2).
242        $events[] = [$start, 2, chr(0x90 | $channel) . chr($note) . chr($velocity)];
243        $events[] = [$start + $length, 1, chr(0x80 | $channel) . chr($note) . chr(0)];
244    }
245
246    /** @param array<int, array{int, int, string}> $events */
247    private function encodeTrack(array $events, int $endTick): string
248    {
249        usort($events, fn (array $a, array $b) => [$a[0], $a[1]] <=> [$b[0], $b[1]]);
250        $data = '';
251        $previous = 0;
252        foreach ($events as [$tick, , $bytes]) {
253            $data .= $this->variableLength($tick - $previous) . $bytes;
254            $previous = $tick;
255        }
256        $data .= $this->variableLength(max(0, $endTick - $previous)) . "\xFF\x2F\x00";
257
258        return 'MTrk' . pack('N', strlen($data)) . $data;
259    }
260
261    private function variableLength(int $value): string
262    {
263        $result = chr($value & 0x7F);
264        while ($value >>= 7) {
265            $result = chr(($value & 0x7F) | 0x80) . $result;
266        }
267        return $result;
268    }
269}