1
0
Fork 0
mirror of https://github.com/Yetangitu/ampache synced 2025-10-04 10:19:25 +02:00

Merge branch 'ogg-channel-streaming' of https://github.com/Deathcow/ampache into Deathcow-ogg-channel-streaming

This commit is contained in:
Afterster 2015-05-30 20:35:46 +02:00
commit dfacb51b3d
2 changed files with 413 additions and 275 deletions

View file

@ -23,6 +23,8 @@
define('NO_SESSION','1'); define('NO_SESSION','1');
define('CLI', 1); define('CLI', 1);
$chunk_buffer = '';
$nb_chunks_remainder = 0;
$path = dirname(__FILE__); $path = dirname(__FILE__);
$prefix = realpath($path . '/../'); $prefix = realpath($path . '/../');
require_once $prefix . '/lib/init.php'; require_once $prefix . '/lib/init.php';
@ -106,7 +108,7 @@ echo T_("Listening on ") . $address . ':' . $port . "\n";
$stream_clients = array(); $stream_clients = array();
$client_socks = array(); $client_socks = array();
$last_stream = 0; $last_stream = microtime(true);
while(true) while(true)
{ {
//prepare readable sockets //prepare readable sockets
@ -114,7 +116,6 @@ while(true)
if (count($client_socks) < $channel->max_listeners) { if (count($client_socks) < $channel->max_listeners) {
$read_socks[] = $server; $read_socks[] = $server;
} }
//echo "b\n";ob_flush(); //echo "b\n";ob_flush();
//start reading and use a large timeout //start reading and use a large timeout
if(stream_select ( $read_socks, $write, $except, 1)) if(stream_select ( $read_socks, $write, $except, 1))
@ -141,11 +142,188 @@ while(true)
// Get new message from existing client // Get new message from existing client
foreach($read_socks as $sock) foreach($read_socks as $sock)
{ {
// Handle data parse
http_serve($channel, $client_socks, $stream_clients, $read_socks, $sock);
}
}
if ($channel->bitrate) {
$time_offset = microtime(true) - $last_stream;
//debug_event('channel', 'time_offset : '. $time_offset, '5');
//debug_event('channel', 'last_stream: '.$last_stream, '5');
if ($time_offset < 1)
usleep(1000000 - ($time_offset * 1000000)); // always at least 1 second between cycles
$last_stream = microtime(true);
$mtime = ($time_offset > 1) ? $time_offset : 1;
$nb_chunks = ceil(($mtime * ($channel->bitrate+1/100*$channel->bitrate) * 1000 / 8) / $channel->chunk_size); // channel->bitrate+1% ... leave some headroom for metadata / headers
// we only send full blocks, save remainder and apply when appropriate: allows more granular/arbitrary average bitrates
if ($nb_chunks - ($mtime * ($channel->bitrate+1/100*$channel->bitrate) * 1000 / 8 / $channel->chunk_size) > 0)
$nb_chunks_remainder += $nb_chunks - ($mtime * $channel->bitrate * 1000 / 8 / $channel->chunk_size);
if ($nb_chunks >= 1 && $nb_chunks_remainder >= 1){
$nb_chunks -= 1;
$nb_chunks_remainder -= 1;
//debug_event('channel', 'REMAINDER: '.$nb_chunks_remainder, '5');
}
//debug_event('channel', 'mtime '.$mtime, '5');
//debug_event('channel', 'nb_chunks: '.$nb_chunks, '5');
} else {
$nb_chunks = 1;
}
// Get multiple chunks according to bitrate to return enough data per second (because sleep with socket select)
for ($c = 0; $c < $nb_chunks; $c++) {
$chunk = $channel->get_chunk();
$chunklen = strlen($chunk);
$chunk_buffer .= $chunk;
//buffer maintenance
while (strlen($chunk_buffer) > (15 * $nb_chunks * $channel->chunk_size) ){ // buffer 15 seconds
if (strtolower($channel->stream_type) == "ogg" && strtohex(substr($chunk_buffer, 0, 4)) == "4F676753") { //maintain ogg chunk alignment --- "4F676753" == "OggS"
// read OggS segment length
$hex = strtohex(substr($chunk_buffer, 0, 27));
$ogg_nr_of_segments = hexdec(substr($hex, 26*2, 2));
$hex .= strtohex(substr($chunk_buffer, 27, $ogg_nr_of_segments));
$ogg_sum_segm_laces = 0;
for($segm = 0; $segm < $ogg_nr_of_segments; $segm++){
$ogg_sum_segm_laces += hexdec(substr($hex, 27*2 + $segm*2, 2));
}
//$naive = strpos(substr($chunk_buffer, 4), 'OggS') + 4; // naive search for next header
//remove 1 whole OggS chunk
$chunk_buffer = substr($chunk_buffer, 27 + $ogg_nr_of_segments + $ogg_sum_segm_laces);
//debug_event('channel', '$new chunk buffer : '.substr($chunk_buffer,0,300) . ' $hex: '.strtohex(substr($chunk_buffer,0,600)) . ' $ogg_nr_of_segments: ' .$ogg_nr_of_segments . ' bytes cut off: '.(27 + $ogg_nr_of_segments + $ogg_sum_segm_laces) . ' naive: ' .$naive, '5');
} elseif (strtolower($channel->stream_type) == "ogg") {
debug_event('channel', 'Ogg alignament broken! Trying repair...', '5');
$manual_search = strpos($chunk_buffer, 'OggS');
$chunk_buffer = substr($chunk_buffer, $manual_search);
} else { // no chunk alignment required
$chunk_buffer = substr($chunk_buffer, $chunklen);
}
//debug_event('channel', 'remvd chunk from buffer ', '5');
}
if ($chunklen > 0) {
foreach($stream_clients as $key => $client)
{
$sock = $client['socket'];
$clchunk = $chunk;
if(!is_resource($sock)) {
client_disconnect($channel, $client_socks, $stream_clients, $sock);
continue;
}
if ($client['isnew'] == 1){
$client['isnew'] = 0;
//fwrite($sock, $channel->header_chunk);
//debug_event('channel', 'IS NEW' . $channel->header_chunk, '5');
$clchunk_buffer = $channel->header_chunk . $chunk_buffer;
if ($client['metadata']){ //stub
//if (strtolower($channel->stream_type) == "ogg")
while(strlen($clchunk_buffer) > $metadata_interval){
fwrite($sock, substr($clchunk_buffer, 0, $metadata_interval) . chr(0x00));
$clchunk_buffer = substr($clchunk_buffer, $metadata_interval);
}
fwrite($sock, $clchunk_buffer);
$client['metadata_lastsent'] = 0;
$client['length'] += strlen($clchunk_buffer);
} else {
//fwrite($sock, $channel->header_chunk);
$buffer_bytes_written = fwrite($sock, $clchunk_buffer);
while ($buffer_bytes_written != strlen($clchunk_buffer)){
debug_event('channel', 'I HERPED WHEN I SHOULD HAVE DERPED!', '5');
//debug_event('channel', 'chunk_buffer bytes written:' .$buffer_bytes_written .'strlen $chunk_buffer: '.strlen($chunk_buffer), '5');
$clchunk_buffer = substr($clchunk_buffer, $buffer_bytes_written);
$buffer_bytes_written = fwrite($sock, $clchunk_buffer);
}
}
$stream_clients[$key] = $client;
continue;
}
// Check if we need to insert metadata information
if ($client['metadata']) {
$chkmdlen = ($client['length'] + $chunklen) - $client['metadata_lastsent'];
if ($chkmdlen >= $metadata_interval) {
$subpos = ($client['metadata_lastsent'] + $metadata_interval) - $client['length'];
fwrite($sock, substr($clchunk, 0, $subpos));
$client['length'] += $subpos;
if ($channel->media->id != $client['metadata_lastsong']) {
$metadata = "StreamTitle='" . str_replace('-', ' ', $channel->media->f_artist) . "-" . $channel->media->f_title . "';";
$metadata .= chr(0x00);
$metadatalen = ceil(strlen($metadata) / 16);
$metadata = str_pad($metadata, $metadatalen * 16, chr(0x00), STR_PAD_RIGHT);
//debug_event('channel', 'Sending metadata to client...', '5');
fwrite($sock, chr($metadatalen) . $metadata);
$client['metadata_lastsong'] = $channel->media->id;
} else {
fwrite($sock, chr(0x00));
}
$client['metadata_lastsent'] = $client['length'];
$clchunk = substr($chunk, $subpos);
}
}
if (strlen($clchunk) > 0) {
fwrite($sock, $clchunk);
$client['length'] += strlen($clchunk);
}
$stream_clients[$key] = $client;
//debug_event('channel', 'Client stream current length: ' . $client['length'], '5');
}
} else {
$channel->update_listeners(0);
die('No more data, stream ended.');
}
}
}
ob_end_flush();
echo "\n";
function client_disconnect($channel, &$client_socks, &$stream_clients, $sock)
{
$key = array_search($sock, $client_socks);
unset($client_socks[$key]);
unset($stream_clients[$key]);
@fclose($sock);
$channel->update_listeners(count($client_socks));
debug_event('channel', 'A client disconnected. Now there are total '. count($client_socks) . ' clients.', '5');
echo "Client disconnected.\n";
ob_flush();
}
function usage()
{
echo T_("- Channel Listening -");
echo "\n";
echo T_("Usage: channel_run.inc [-c {CHANNEL ID}|-p {PORT}|-v]");
echo "\n\t";
echo "\n-c {CHANNEL ID}\t";
echo T_('Channel id to start');
echo "\n-p {PORT}\t";
echo T_('Listening port, default get an available port automatically');
echo "\n-v\t";
echo T_('Verbose');
echo "\n";
echo "----------------------------------------------------------";
echo "\n";
}
function http_serve($channel, &$client_socks, &$stream_clients, &$read_socks, $sock)
{
$data = fread($sock, 1024); $data = fread($sock, 1024);
if(!$data) if(!$data)
{ {
client_disconnect($channel, $client_socks, $stream_clients, $sock); client_disconnect($channel, $client_socks, $stream_clients, $sock);
continue; return;
} }
$headers = explode("\n", $data); $headers = explode("\n", $data);
@ -157,9 +335,11 @@ while(true)
case '/stream.' . $channel->stream_type: case '/stream.' . $channel->stream_type:
$options = array( $options = array(
'socket' => $sock, 'socket' => $sock,
'length' => 0 'length' => 0,
'isnew' => 1
); );
//debug_event('channel', 'HTTP HEADERS: '.$data,'5');
for ($i = 1; $i < count($headers); $i++) { for ($i = 1; $i < count($headers); $i++) {
$headerpart = explode(":", $headers[$i], 2); $headerpart = explode(":", $headers[$i], 2);
$header = strtolower(trim($headerpart[0])); $header = strtolower(trim($headerpart[0]));
@ -175,42 +355,45 @@ while(true)
// Stream request // Stream request
if ($options['metadata']) { if ($options['metadata']) {
//fwrite($sock, "ICY 200 OK\r\n"); //$http = "ICY 200 OK\r\n");
fwrite($sock, "HTTP/1.0 200 OK\r\n"); $http = "HTTP/1.0 200 OK\r\n";
} else { } else {
fwrite($sock, "HTTP/1.1 200 OK\r\n"); $http = "HTTP/1.1 200 OK\r\n";
fwrite($sock, "Cache-Control: no-store, no-cache, must-revalidate\r\n"); $http .= "Cache-Control: no-store, no-cache, must-revalidate\r\n";
} }
fwrite($sock, "Content-Type: " . Song::type_to_mime($channel->stream_type) . "\r\n"); $http .= "Content-Type: " . Song::type_to_mime($channel->stream_type) . "\r\n";
fwrite($sock, "Accept-Ranges: none\r\n"); $http .= "Accept-Ranges: none\r\n";
$genre = $channel->get_genre(); $genre = $channel->get_genre();
// Send Shoutcast metadata on demand // Send Shoutcast metadata on demand
if ($options['metadata']) { //if ($options['metadata']) {
fwrite($sock, "icy-notice1: " . AmpConfig::get('site_title') . "\r\n"); $http .= "icy-notice1: " . AmpConfig::get('site_title') . "\r\n";
fwrite($sock, "icy-name: " . $channel->name . "\r\n"); $http .= "icy-name: " . $channel->name . "\r\n";
if (!empty($genre)) { if (!empty($genre)) {
fwrite($sock, "icy-genre: " . $genre . "\r\n"); $http .= "icy-genre: " . $genre . "\r\n";
} }
fwrite($sock, "icy-url: " . $channel->url . "\r\n"); $http .= "icy-url: " . $channel->url . "\r\n";
fwrite($sock, "icy-pub: " . ($channel->is_private) ? '0' : '1' . "\r\n"); $http .= "icy-pub: " . (($channel->is_private) ? "0" : "1") . "\r\n";
if ($channel->bitrate) { if ($channel->bitrate) {
fwrite($sock, "icy-br: " . strval($channel->bitrate) . "\r\n"); $http .= "icy-br: " . strval($channel->bitrate) . "\r\n";
}
fwrite($sock, "icy-metaint: " . strval($metadata_interval) . "\r\n");
} }
global $metadata_interval;
$http .= "icy-metaint: " . strval($metadata_interval) . "\r\n";
//}
// Send additional Icecast metadata // Send additional Icecast metadata
fwrite($sock, "x-audiocast-server-url: " . $channel->url . "\r\n"); $http .= "x-audiocast-server-url: " . $channel->url . "\r\n";
fwrite($sock, "x-audiocast-name: " . $channel->name . "\r\n"); $http .= "x-audiocast-name: " . $channel->name . "\r\n";
fwrite($sock, "x-audiocast-description: " . $channel->description . "\r\n"); $http .= "x-audiocast-description: " . $channel->description . "\r\n";
fwrite($sock, "x-audiocast-url: " . $channel->url . "\r\n"); $http .= "x-audiocast-url: " . $channel->url . "\r\n";
if (!empty($genre)) { if (!empty($genre)) {
fwrite($sock, "x-audiocast-genre: " . $genre . "\r\n"); $http .= "x-audiocast-genre: " . $genre . "\r\n";
} }
fwrite($sock, "x-audiocast-bitrate: " . strval($channel->bitrate) . "\r\n"); $http .= "x-audiocast-bitrate: " . strval($channel->bitrate) . "\r\n";
fwrite($sock, "x-audiocast-public: " . (($channel->is_private) ? "0" : "1") . "\r\n"); $http .= "x-audiocast-public: " . (($channel->is_private) ? "0" : "1") . "\r\n";
fwrite($sock, "\r\n"); $http .= "\r\n";
fwrite($sock, $http);
// Add to stream clients list // Add to stream clients list
$key = array_search($sock, $read_socks); $key = array_search($sock, $read_socks);
@ -383,106 +566,12 @@ while(true)
} }
} }
} }
// Handle data parse
}
}
if ($channel->bitrate) {
$time_offset = microtime(true) - $last_stream;
$mtime = ($last_stream > 0 && $time_offset < 1) ? $time_offset : 1;
if ($last_stream > 0 && $time_offset < 1) {
usleep(1000000 - ($time_offset * 1000000));
} elseif ($last_stream > 0) {
//$mtime = $time_offset;
}
$nb_chunks = ceil(($mtime * $channel->bitrate * 1000) / 4096);
} else {
$nb_chunks = 1;
}
// Get multiple chunks according to bitrate to return enough data per second (because sleep with socket select)
for ($c = 0; $c < $nb_chunks; $c++) {
$chunk = $channel->get_chunk();
$chunklen = strlen($chunk);
if ($chunklen > 0) {
foreach($stream_clients as $key => $client)
{
$sock = $client['socket'];
if(!is_resource($sock)) {
client_disconnect($channel, $client_socks, $stream_clients, $sock);
continue;
}
$clchunk = $chunk;
// Check if we need to insert metadata information
if ($client['metadata']) {
$chkmdlen = ($client['length'] + $chunklen) - $client['metadata_lastsent'];
if ($chkmdlen >= $metadata_interval) {
$subpos = ($client['metadata_lastsent'] + $metadata_interval) - $client['length'];
fwrite($sock, substr($clchunk, 0, $subpos));
$client['length'] += $subpos;
if ($channel->media->id != $client['metadata_lastsong']) {
$metadata = "StreamTitle='" . str_replace('-', ' ', $channel->media->f_artist) . "-" . $channel->media->f_title . "';";
$metadata .= chr(0x00);
$metadatalen = ceil(strlen($metadata) / 16);
$metadata = str_pad($metadata, $metadatalen * 16, chr(0x00), STR_PAD_RIGHT);
//debug_event('channel', 'Sending metadata to client...', '5');
fwrite($sock, chr($metadatalen) . $metadata);
$client['metadata_lastsong'] = $channel->media->id;
} else {
fwrite($sock, chr(0x00));
}
$client['metadata_lastsent'] = $client['length'];
$clchunk = substr($chunk, $subpos);
}
}
if (strlen($clchunk) > 0) {
fwrite($sock, $clchunk);
$client['length'] += strlen($clchunk);
}
$stream_clients[$key] = $client;
//debug_event('channel', 'Client stream current length: ' . $client['length'], '5');
}
} else {
$channel->update_listeners(0);
die('No more data, stream ended.');
}
$last_stream = microtime(true);
}
} }
ob_end_flush(); function strtohex($x) {
echo "\n"; $s='';
foreach(str_split($x) as $c) $s.=sprintf("%02X",ord($c));
function client_disconnect($channel, &$client_socks, &$stream_clients, $sock) return($s);
{
$key = array_search($sock, $client_socks);
unset($client_socks[$key]);
unset($stream_clients[$key]);
@fclose($sock);
$channel->update_listeners(count($client_socks));
debug_event('channel', 'A client disconnected. Now there are total '. count($client_socks) . ' clients.', '5');
echo "Client disconnected.\n";
ob_flush();
}
function usage()
{
echo T_("- Channel Listening -");
echo "\n";
echo T_("Usage: channel_run.inc [-c {CHANNEL ID}|-p {PORT}|-v]");
echo "\n\t";
echo "\n-c {CHANNEL ID}\t";
echo T_('Channel id to start');
echo "\n-p {PORT}\t";
echo T_('Listening port, default get an available port automatically');
echo "\n-v\t";
echo T_('Verbose');
echo "\n";
echo "----------------------------------------------------------";
echo "\n";
} }
?> ?>

View file

@ -39,6 +39,10 @@ class Channel extends database_object implements media, library_item
public $name; public $name;
public $description; public $description;
public $header_chunk;
public $chunk_size = 4096;
private $header_chunk_remainder = 0;
public $tags; public $tags;
public $f_tags; public $f_tags;
@ -419,10 +423,47 @@ class Channel extends database_object implements media, library_item
} }
if (is_resource($this->transcoder['handle'])) { if (is_resource($this->transcoder['handle'])) {
if (ftell($this->transcoder['handle']) == 0)
$chunk = fread($this->transcoder['handle'], 4096); $this->header_chunk = '';
$chunk = fread($this->transcoder['handle'], $this->chunk_size);
$this->media_bytes_streamed += strlen($chunk); $this->media_bytes_streamed += strlen($chunk);
if ((ftell($this->transcoder['handle']) < 10000 && strtolower($this->stream_type) == "ogg") || $this->header_chunk_remainder) {
//debug_event('channel', 'File handle pointer: ' . ftell($this->transcoder['handle']) ,'5');
$clchunk = $chunk;
if ($this->header_chunk_remainder) {
$this->header_chunk .= substr($clchunk, 0, $this->header_chunk_remainder);
if (strlen($clchunk) >= $this->header_chunk_remainder) {
$clchunk = substr($clchunk, $this->header_chunk_remainder);
$this->header_chunk_remainder = 0;
} else {
$this->header_chunk_remainder = $this->header_chunk_remainder - strlen($clchunk);
$clchunk = '';
}
}
// see bin/channel_run.inc for explanation what's happening here
while ($this->strtohex(substr($clchunk, 0, 4)) == "4F676753") {
$hex = $this->strtohex(substr($clchunk, 0, 27));
$ogg_nr_of_segments = hexdec(substr($hex, 26*2, 2));
if ((substr($clchunk, 27 + $ogg_nr_of_segments + 1, 6) == "vorbis") || (substr($clchunk, 27 + $ogg_nr_of_segments, 4) == "Opus")) {
$hex .= $this->strtohex(substr($clchunk, 27, $ogg_nr_of_segments));
$ogg_sum_segm_laces = 0;
for ($segm = 0; $segm < $ogg_nr_of_segments; $segm++) {
$ogg_sum_segm_laces += hexdec(substr($hex, 27*2 + $segm*2, 2));
}
$this->header_chunk .= substr($clchunk, 0, 27 + $ogg_nr_of_segments + $ogg_sum_segm_laces);
if (strlen($clchunk) < (27 + $ogg_nr_of_segments + $ogg_sum_segm_laces))
$this->header_chunk_remainder = (int) (27 + $ogg_nr_of_segments + $ogg_sum_segm_laces - strlen($clchunk));
$clchunk = substr($clchunk, 27 + $ogg_nr_of_segments + $ogg_sum_segm_laces);
} else //no more interesting headers
$clchunk = '';
}
}
//debug_event('channel', 'File handle pointer: ' . ftell($this->transcoder['handle']) ,'5');
//debug_event('channel', 'CHUNK : ' . $chunk, '5');
//debug_event('channel', 'Chunk size: ' . strlen($chunk) ,'5');
// End of file, prepare to move on for next call // End of file, prepare to move on for next call
if (feof($this->transcoder['handle'])) { if (feof($this->transcoder['handle'])) {
$this->media->set_played(-1, 'Ampache', array()); $this->media->set_played(-1, 'Ampache', array());
@ -493,4 +534,12 @@ class Channel extends database_object implements media, library_item
} }
private function strtohex($x)
{
$s='';
foreach(str_split($x) as $c) $s.=sprintf("%02X",ord($c));
return($s);
}
} // end of channel class } // end of channel class