<?php
  include_once "./audiostreamerlib.php";

  //  AudioStreamer, www.audiostreamer.org
  //  Copyright (C) <2013>  <Lieven Rottiers>
  //
  //  This program is free software: you can redistribute it and/or modify
  //  it under the terms of the GNU General Public License as published by
  //  the Free Software Foundation, either version 3 of the License, or
  //  (at your option) any later version.
  //
  //  This program is distributed in the hope that it will be useful,
  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  //  GNU General Public License for more details.
  //
  //  You should have received a copy of the GNU General Public License
  //  along with this program.  If not, see <http://www.gnu.org/licenses/>.

  $id = $_GET["id"];
  $resampling = $_SESSION["ind_resampling"];
  $bitrate = $_SESSION["bitrate"];
  $normalizing = $_SESSION["ind_normalizing"];
  $file = '';
  $filesize = 0;
  $cmd = '';
  
  try {
    global $sdb;
    $dbh = new PDO("sqlite:".$sdb);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);

    $sql = "select path, length_seconds, 
                   ifnull(nullif(song_gain,''), '-6.00 db') as song_gain, 
                   ifnull(nullif(album_gain,''), '-6.00 db') as album_gain 
            from music where id = ".$id;
    foreach ($dbh->query($sql) as $row) {
      $file = $row['path'];
    }   
    
    //close connection
    $dbh = null;
  }
  catch(PDOException $e)
  {
    echo '<br/>'.$e->getMessage();
  }  

  if (file_exists($file)) {
    if ($resampling == '1') {
		  //if ffmpeg.exe file not exists in root directory then no resmapling
			if (!file_exists("./ffmpeg.exe")) {
				$resampling = '0';
			}
		}
    if ($resampling == '1') {
      //resample the file and read back the results
      
      //calculate filesize in bytes
      //this doesn't work when there are no id3 tags available (length_seconds is empty)
      if (!empty($row['length_seconds'])) {
        $filesize = round(($row['length_seconds'] * $bitrate)*1000/8);      
        header('Content-Length: ' . $filesize);
      }
      
      //-vol makes adjustment to volume, 256 means no change in volume
      if ($normalizing == '1') {
        //calculate gain percentage
        //
        //if no gain is found in database then the default is -6db
        $gain = pow(10,str_replace(" db","",$row['song_gain'])/20);
      }
      else {
        $gain = 1;
      }
      $cmd = "ffmpeg -i \"".$file."\" -v 0 -ab ".($bitrate*1000)." -vol ".round(256*$gain)." -f mp3 -";
      
      header("Cache-Control: no-cache, must-revalidate");
      header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
      header("Content-Type: audio/mpeg"); 

      ob_clean();
      flush();

      passthru($cmd);

      exit;
    }
    else {
      //No resampling, nothing, just throw the audio file...
      header('Content-Description: File Transfer');
      //header('Accept-Ranges: bytes');
      header("Content-Type: audio/mpeg"); 
      header('Content-Transfer-Encoding: binary');
      header('Expires: 0');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file));
      ob_clean();
      flush();
      readfile($file);
      exit;
    }
  }
?>