setup howto
[noxon-gateway.git] / www / transcode-nocache.php
1 <?php
2 /**
3  * Transcode audio file URLs to .mp3 and stream it while
4  * transcoding is in progress.
5  */
6 //require_once __DIR__ . '/../src/header.php';
7
8 if (!isset($_GET['url'])) {
9     errorOut('url parameter missing');
10 }
11 $parts = parse_url($_GET['url']);
12 if ($parts === false || !isset($parts['scheme'])) {
13     errorOut('Invalid URL');
14 }
15 if ($parts['scheme'] !== 'http' && $parts['scheme'] !== 'https') {
16     errorOut('URL is neither http nor https');
17 }
18 $url = $_GET['url'];
19
20 $cmd = 'ffmpeg'
21     . ' -loglevel error'
22     . ' -i ' . escapeshellarg($url)
23     . ' -f mp3'
24     . ' -';
25
26 $descriptorspec = array(
27     1 => array('pipe', 'w'),// stdout is a pipe that the child will write to
28     2 => array('pipe', 'w')//stderr
29 );
30
31 register_shutdown_function('shutdown');
32
33 $process = proc_open($cmd, $descriptorspec, $pipes);
34 if (is_resource($process)) {
35     header('Content-type: audio/mpeg');
36     while ($data = fread($pipes[1], 10000)) {
37         //output to browser
38         echo $data;
39         //TODO: maybe flush() and ob_flush();
40     }
41
42     $errors = stream_get_contents($pipes[2]);
43     fclose($pipes[1]);
44     fclose($pipes[2]);
45     $retval = proc_close($process);
46
47     if ($retval !== 0) {
48         header('HTTP/1.0 500 Internal Server Error');
49         header('Content-type: text/plain');
50         echo "Error transcoding\n";
51         echo $errors . "\n";
52     }
53 }
54
55 function shutdown()
56 {
57     global $process, $pipes;
58
59     if (connection_aborted()) {
60         //end ffmpeg and clean temp file
61         fclose($pipes[1]);
62         fclose($pipes[2]);
63         proc_terminate($process);
64     }
65 }
66
67 function errorOut($msg)
68 {
69     header('HTTP/1.0 400 Bad request');
70     header('Content-type: text/plain');
71     echo $msg . "\n";
72     exit(1);
73 }
74 ?>