Passed
Pull Request — master (#1079)
by
unknown
11:38
created

TranscodingStreamer::stream()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 42
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 42
ccs 0
cts 28
cp 0
rs 8.8337
c 0
b 0
f 0
cc 6
nc 10
nop 0
crap 42
1
<?php
2
3
namespace App\Services\Streamers;
4
5
class TranscodingStreamer extends Streamer implements TranscodingStreamerInterface
6
{
7
    /**
8
     * Bit rate the stream should be transcoded at.
9
     *
10
     * @var int
11
     */
12
    private $bitRate;
13
14
    /**
15
     * Time point to start transcoding from.
16
     *
17
     * @var float
18
     */
19
    private $startTime;
20
21
    /**
22
     * On-the-fly stream the current song while transcoding.
23
     */
24
    public function stream(): void
25
    {
26
        $ffmpeg = config('koel.streaming.ffmpeg_path');
27
	$codec = config('koel.streaming.ffmpeg_codec');
28
        abort_unless(is_executable($ffmpeg), 500, 'Transcoding requires valid ffmpeg settings.');
29
30
	//used the chart on https://en.wikipedia.org/wiki/HTML5_audio#Supported_audio_coding_formats to match up formats to container types.
31
	$container = null;
32
	switch($codec)
33
	{
34
	   case 'libopus':
35
	   case 'libvorbis':
36
	      $container = 'ogg';
37
	      break;
38
	   case 'libmp3lame':
39
	      $container = 'mp3';
40
	      break;
41
	   case 'aac':
42
	      $container = 'adts';
43
	      break;
44
	}
45
46
        $bitRate = filter_var($this->bitRate, FILTER_SANITIZE_NUMBER_INT);
47
48
        header('Content-Type: audio/mpeg');
49
        header('Content-Disposition: attachment; filename="'.basename($this->song->path).'"');
50
51
        $args = [
52
            '-i '.escapeshellarg($this->song->path),
53
            '-map 0:0',
54
            '-v 0',
55
	    "-b:a {$bitRate}k",
56
	    "-c:a {$codec}",
57
            "-f {$container}",
58
            '-',
59
        ];
60
61
        if ($this->startTime) {
62
            array_unshift($args, "-ss {$this->startTime}");
63
        }
64
65
        passthru("$ffmpeg ".implode($args, ' '));
0 ignored issues
show
Bug introduced by
' ' of type string is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

65
        passthru("$ffmpeg ".implode($args, /** @scrutinizer ignore-type */ ' '));
Loading history...
66
    }
67
68 2
    public function setBitRate(int $bitRate): void
69
    {
70 2
        $this->bitRate = $bitRate;
71 2
    }
72
73 2
    public function setStartTime(float $startTime): void
74
    {
75 2
        $this->startTime = $startTime;
76 2
    }
77
}
78