<?php
require_once("admin/inc/protecao-final.php");

$total_avisos_ativos = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM avisos WHERE area = 'streaming'"));
$checar_status_aviso = mysqli_num_rows(mysqli_query($conexao,"SELECT * FROM avisos_desativados WHERE area = 'streaming' AND login = '".$dados_stm["login"]."'"));
$total_avisos_exibir = ($total_avisos_ativos > $checar_status_aviso) ? $total_avisos_ativos-$checar_status_aviso : 0;

if(query_string('1') == "instalar" && $dados_stm["transcoder"] == "sim") {

mysqli_query($conexao,"Update streamings set transcoder_instalado = 'sim' where codigo = '".$dados_stm["codigo"]."'");

// Conexão SSH
$ssh = new SSH();
$ssh->conectar($dados_servidor["ip"],$dados_servidor["porta_ssh"]);
$ssh->autenticar("root",code_decode($dados_servidor["senha"],"D"));

$ssh->executar("perl -i -p -e \"s/<LiveStreamTranscoder><\/LiveStreamTranscoder>/<LiveStreamTranscoder>transcoder<\/LiveStreamTranscoder>/\" /usr/local/WowzaStreamingEngine/conf/".$dados_stm["login"]."/Application.xml");

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = "<div class='alert alert-success text-center' role='alert'>Transcoder instalado com sucesso! Agora voc&ecirc; deve configurar as qualidades desejadas</div>";

header("Location: /configuracoes-transcoder");
exit();
}

if(isset($_POST["alterar"])) {

if(count($_POST["qualidades"]) > 0){
  $transcoder_qualidades = implode("|",$_POST["qualidades"]);
}

// Atualiza as qualidades
mysqli_query($conexao,"Update streamings set transcoder_qualidades = '".$transcoder_qualidades."' where codigo = '".$dados_stm["codigo"]."'");

// Atualiza o arquivo /home/streaming/LOGIN/transcoder.smil
$conteudo_transcoder .= "<smil>\n";
$conteudo_transcoder .= "<head></head>\n";
$conteudo_transcoder .= "<body>\n";
$conteudo_transcoder .= "<switch>\n";

foreach($_POST['qualidades'] as $qualidade) {

if($qualidade == "1080p") {
$conteudo_transcoder .= '<video src="mp4:'.$dados_stm["login"].'_1080p" system-bitrate="2046000" width="1920" height="1080">
<param name="audioBitrate" value="96000" valuetype="data"/>
<param name="videoBitrate" value="1950000" valuetype="data"/>
</video>';
}
if($qualidade == "720p") {
$conteudo_transcoder .= '<video src="mp4:'.$dados_stm["login"].'_720p" system-bitrate="1396000" width="1280" height="720">
<param name="audioBitrate" value="96000" valuetype="data"/>
<param name="videoBitrate" value="1300000" valuetype="data"/>
</video>';
}
if($qualidade == "360p") {
$conteudo_transcoder .= '<video src="mp4:'.$dados_stm["login"].'_360p" system-bitrate="1024000" width="640" height="360">
<param name="audioBitrate" value="96000" valuetype="data"/>
<param name="videoBitrate" value="928000" valuetype="data"/>
</video>';
}
if($qualidade == "240p") {
$conteudo_transcoder .= '<video src="mp4:'.$dados_stm["login"].'_240p" system-bitrate="446000" width="426" height="240">
<param name="audioBitrate" value="96000" valuetype="data"/>
<param name="videoBitrate" value="350000" valuetype="data"/>
</video>';
}
if($qualidade == "160p") {
$conteudo_transcoder .= '<video src="mp4:'.$dados_stm["login"].'_160p" system-bitrate="296000" width="284" height="160">
<param name="audioBitrate" value="96000" valuetype="data"/>
<param name="videoBitrate" value="200000" valuetype="data"/>
</video>';
}

}

$conteudo_transcoder .= "</switch>\n";
$conteudo_transcoder .= "</body>\n";
$conteudo_transcoder .= "</smil>\n";

$handle_transcoder = fopen("temp/".$dados_stm["login"]."_transcoder.smil" ,"w");
fwrite($handle_transcoder, $conteudo_transcoder);
fclose($handle_transcoder);

$qualidade_1080p = (strpos($dados_stm["transcoder_qualidades"], '1080p') !== false) ? "true" : "false";
$qualidade_720p = (strpos($dados_stm["transcoder_qualidades"], '720p') !== false) ? "true" : "false";

$conteudo_transcoder_wowza = '<?xml version="1.0" encoding="UTF-8" ?>
<Root version="1">
  <Transcode>
    <Description>Transcoder para '.$dados_stm["login"].'</Description>
    <Encodes>

      <Encode>
        <Enable>'.$qualidade_1080p.'</Enable>
        <Name>1080p</Name>
        <StreamName>mp4:${SourceStreamName}_1080p</StreamName>
        <Video>
          <Codec>H.264</Codec>
          <Implementation>default</Implementation>
          <GPUID>-1</GPUID>
          <FrameSize>
            <FitMode>fit-height</FitMode>
            <Width>1920</Width>
            <Height>1080</Height>
          </FrameSize>
          <Profile>main</Profile>
          <Bitrate>1952000</Bitrate>
          <KeyFrameInterval>
            <FollowSource>false</FollowSource>
            <Interval>60</Interval>
          </KeyFrameInterval>
          <Overlays>
            <Overlay>
              <Enable>false</Enable>
              <Name>Logo</Name>
              <Index>0</Index>
              <ImagePath>/home/streaming/'.$dados_stm["login"].'/logo-watermark.png</ImagePath>
              <CheckForUpdates>true</CheckForUpdates>
              <Opacity>100</Opacity>
              <Location>
                <X>10</X>
                <Y>10</Y>
                <Width>${ImageWidth}</Width>
                <Height>${ImageHeight}</Height>
                <Align>right,bottom</Align>
              </Location>
            </Overlay>
          </Overlays>
          <Parameters>
          </Parameters>
        </Video>
        <Audio>
          <Codec>PassThru</Codec>
          <Bitrate>96000</Bitrate>
          <Parameters>
          </Parameters>
        </Audio>
        <Properties>
        </Properties>
      </Encode>

      <Encode>
        <Enable>'.$qualidade_720p.'</Enable>
        <Name>720p</Name>
        <StreamName>mp4:${SourceStreamName}_720p</StreamName>
        <Video>
          <Codec>H.264</Codec>
          <Implementation>default</Implementation>
          <GPUID>-1</GPUID>
          <FrameSize>
            <FitMode>fit-height</FitMode>
            <Width>1280</Width>
            <Height>720</Height>
          </FrameSize>
          <Profile>main</Profile>
          <Bitrate>1300000</Bitrate>
          <KeyFrameInterval>
            <FollowSource>false</FollowSource>
            <Interval>60</Interval>
          </KeyFrameInterval>
          <Overlays>
            <Overlay>
              <Enable>false</Enable>
              <Name>Logo</Name>
              <Index>0</Index>
              <ImagePath>/home/streaming/'.$dados_stm["login"].'/logo-watermark.png</ImagePath>
              <CheckForUpdates>true</CheckForUpdates>
              <Opacity>100</Opacity>
              <Location>
                <X>10</X>
                <Y>10</Y>
                <Width>${ImageWidth}</Width>
                <Height>${ImageHeight}</Height>
                <Align>right,bottom</Align>
              </Location>
            </Overlay>
          </Overlays>
          <Parameters>
          </Parameters>
        </Video>
        <Audio>
          <Codec>PassThru</Codec>
          <Bitrate>96000</Bitrate>
          <Parameters>
          </Parameters>
        </Audio>
        <Properties>
        </Properties>
      </Encode>

      <Encode>
        <Enable>true</Enable>
        <Name>360p</Name>
        <StreamName>mp4:${SourceStreamName}_360p</StreamName>
        <Video>
          <Codec>H.264</Codec>
          <Implementation>default</Implementation>
          <GPUID>-1</GPUID>
          <FrameSize>
            <FitMode>fit-height</FitMode>
            <Width>640</Width>
            <Height>360</Height>
          </FrameSize>
          <Profile>main</Profile>
          <Bitrate>928000</Bitrate>
          <KeyFrameInterval>
            <FollowSource>false</FollowSource>
            <Interval>60</Interval>
          </KeyFrameInterval>
          <Overlays>
            <Overlay>
              <Enable>false</Enable>
              <Name>Logo</Name>
              <Index>0</Index>
              <ImagePath>/home/streaming/'.$dados_stm["login"].'/logo-watermark.png</ImagePath>
              <CheckForUpdates>true</CheckForUpdates>
              <Opacity>100</Opacity>
              <Location>
                <X>10</X>
                <Y>10</Y>
                <Width>${ImageWidth}</Width>
                <Height>${ImageHeight}</Height>
                <Align>right,bottom</Align>
              </Location>
            </Overlay>
          </Overlays>
          <Parameters>
          </Parameters>
        </Video>
        <Audio>
          <Codec>PassThru</Codec>
          <Bitrate>96000</Bitrate>
          <Parameters>
          </Parameters>
        </Audio>
        <Properties>
        </Properties>
      </Encode>

      <Encode>
        <Enable>true</Enable>
        <Name>240p</Name>
        <StreamName>mp4:${SourceStreamName}_240p</StreamName>
        <Video>
          <Codec>H.264</Codec>
          <Implementation>default</Implementation>
          <GPUID>-1</GPUID>
          <FrameSize>
            <FitMode>fit-height</FitMode>
            <Width>360</Width>
            <Height>240</Height>
          </FrameSize>
          <Profile>baseline</Profile>
          <Bitrate>350000</Bitrate>
          <KeyFrameInterval>
            <FollowSource>false</FollowSource>
            <Interval>60</Interval>
          </KeyFrameInterval>
          <Overlays>
            <Overlay>
              <Enable>false</Enable>
              <Name>Logo</Name>
              <Index>0</Index>
              <ImagePath>/home/streaming/'.$dados_stm["login"].'/logo-watermark.png</ImagePath>
              <CheckForUpdates>true</CheckForUpdates>
              <Opacity>100</Opacity>
              <Location>
                <X>10</X>
                <Y>10</Y>
                <Width>${ImageWidth}</Width>
                <Height>${ImageHeight}</Height>
                <Align>right,bottom</Align>
              </Location>
            </Overlay>
          </Overlays>
          <Parameters>
          </Parameters>
        </Video>
        <Audio>
          <Codec>PassThru</Codec>
          <Bitrate>96000</Bitrate>
          <Parameters>
          </Parameters>
        </Audio>
        <Properties>
        </Properties>
      </Encode>

      <Encode>
        <Enable>true</Enable>
        <Name>160p</Name>
        <StreamName>mp4:${SourceStreamName}_160p</StreamName>
        <Video>
          <Codec>H.264</Codec>
          <Implementation>default</Implementation>
          <GPUID>-1</GPUID>
          <FrameSize>
            <FitMode>fit-height</FitMode>
            <Width>284</Width>
            <Height>160</Height>
          </FrameSize>
          <Profile>baseline</Profile>
          <Bitrate>200000</Bitrate>
          <KeyFrameInterval>
            <FollowSource>false</FollowSource>
            <Interval>60</Interval>
          </KeyFrameInterval>
          <Overlays>
            <Overlay>
              <Enable>false</Enable>
              <Name>Logo</Name>
              <Index>0</Index>
              <ImagePath>/home/streaming/'.$dados_stm["login"].'/logo-watermark.png</ImagePath>
              <CheckForUpdates>true</CheckForUpdates>
              <Opacity>100</Opacity>
              <Location>
                <X>10</X>
                <Y>10</Y>
                <Width>${ImageWidth}</Width>
                <Height>${ImageHeight}</Height>
                <Align>right,bottom</Align>
              </Location>
            </Overlay>
          </Overlays>
          <Parameters>
          </Parameters>
        </Video>
        <Audio>
          <Codec>PassThru</Codec>
          <Bitrate>96000</Bitrate>
          <Parameters>
          </Parameters>
        </Audio>
        <Properties>
        </Properties>
      </Encode>
    </Encodes>
    <Properties>
    </Properties>
  </Transcode>
</Root>
';

$handle_transcoder_wowza = fopen("temp/".$dados_stm["login"]."_transcoder.xml" ,"w");
fwrite($handle_transcoder_wowza, $conteudo_transcoder_wowza);
fclose($handle_transcoder_wowza);
  
// Conexão SSH
$ssh = new SSH();
$ssh->conectar($dados_servidor["ip"],$dados_servidor["porta_ssh"]);
$ssh->autenticar("root",code_decode($dados_servidor["senha"],"D"));
  
$ssh->enviar_arquivo("temp/".$dados_stm["login"]."_transcoder.smil","/home/streaming/".$dados_stm["login"]."/transcoder.smil",0600);

$ssh->enviar_arquivo("temp/".$dados_stm["login"]."_transcoder.xml","/usr/local/WowzaStreamingEngine/transcoder/templates/".$dados_stm["login"].".xml",0777);

@unlink("temp/".$dados_stm["login"]."_transcoder.smil");
@unlink("temp/".$dados_stm["login"]."_transcoder.xml");

$ssh->executar("/usr/bin/java -cp /usr/local/WowzaMediaServer JMXCommandLine -jmx service:jmx:rmi://localhost:8084/jndi/rmi://localhost:8085/jmxrmi -user admin -pass admin shutdownAppInstance ".$dados_stm["login"]."");

$ssh->executar("/usr/bin/java -cp /usr/local/WowzaMediaServer JMXCommandLine -jmx service:jmx:rmi://localhost:8084/jndi/rmi://localhost:8085/jmxrmi -user admin -pass admin startAppInstance  ".$dados_stm["login"]."");

// Cria o sessão do status das ações executadas e redireciona.
$_SESSION["status_acao"] = "<div class='alert alert-success text-center' role='alert'>Configura&ccedil;&atilde;o alterada com sucesso.</div>";

header("Location: /configuracoes-transcoder");
exit();

}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Streaming <?php echo $dados_stm["login"]; ?></title>
  <link rel="stylesheet" href="/inc/materialdesignicons.min.css">
  <link rel="stylesheet" href="/inc/font-awesome.min.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.base.css">
  <link rel="stylesheet" href="/inc/vendor.bundle.addons.css">  
  <?php if($dados_stm["tema_dark"] == "sim") { ?>
  <link rel="stylesheet" href="/inc/theme-dark.css">
  <?php } else { ?>
  <link rel="stylesheet" href="/inc/theme.css">
  <?php } ?>
  <link rel="shortcut icon" href="/img/favicon.ico" />
  <script type="text/javascript" src="/inc/ajax-streaming.js"></script>
  <script type="text/javascript" src="/inc/javascript.js"></script>
</head>
<body>
  <div class="container-scroller">
    <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
      <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
        <?php if($dados_revenda["url_logo"]) { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><img id="logo" src="<?php echo $dados_revenda["url_logo"]; ?>" title="Painel" height="60" border="0"></a>
        <?php } else { ?>
        <a class="navbar-brand brand-logo" href="/dashboard"><span>Painel Streaming</span></a>
        <?php } ?>
        <a class="navbar-brand brand-logo-mini" href="/dashboard"><i class="fa fa-video-camera text-muted"></i></a>
      </div>
      <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end justify-content-lg-start">
        <button class="navbar-toggler navbar-toggler align-self-center" type="button" data-toggle="minimize">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
        <ul class="navbar-nav navbar-nav-right">
          <li class="nav-item nav-profile dropdown show">
            <a class="nav-link dropdown-toggle" href="#" data-toggle="dropdown" id="profileDropdown" aria-expanded="true">
              <i class="fa fa-power-off f-18 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_botao_titulo_ligar']; ?>/<?php echo $lang['lang_botao_titulo_desligar']; ?>"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="profileDropdown">
              <a class="dropdown-item text-success" href="javascript:ligar_streaming('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_ligar']; ?> Streaming</a>
              <a class="dropdown-item text-warning" href="javascript:reiniciar_streaming('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_reiniciar']; ?> Streaming</a>
              <?php if($dados_stm["srt_status"] == 'sim') { ?>
              <a class="dropdown-item text-primary" href="javascript:reiniciar_srt('<?php echo $login_code; ?>');"> <?php echo $lang['lang_botao_titulo_reiniciar']; ?> SRT</a>
              <?php } ?>
            </div>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link count-indicator dropdown-toggle d-flex align-items-center justify-content-center" id="notificationDropdown" href="#" data-toggle="dropdown" aria-expanded="false">
              <i class="mdi mdi-bell f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="<?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?>"></i>
              <?php if($total_avisos_exibir > 0) { ?><span class="count bg-success"><?php echo $total_avisos_exibir; ?></span><?php } ?>           
            </a>
            <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list" aria-labelledby="notificationDropdown">
              <a class="dropdown-item">
                <p class="mb-0 font-weight-normal float-left"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></p>
              </a>
              <div class="dropdown-divider"></div>
              <?php carregar_avisos_streaming($conexao,$dados_stm["porta"],$dados_servidor["codigo"]); ?>
            </div>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/sair"><i class="mdi mdi-logout f-22 text-icones" data-toggle="tooltip" data-placement="bottom" title="Sair/logout"></i></a>
          </li>
          <li>
            <button type="button" class="btn btn-info" id="status-streaming" onClick="status_streaming('<?php echo $login_code; ?>');" style="margin: 10px;min-width: 150px; min-height: 40px"><i class="fa fa-refresh"></i></button>
          </li>
        </ul>
        <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas">
          <span class="mdi mdi-menu text-icones"></span>
        </button>
      </div>
    </nav>
    <div class="container-fluid page-body-wrapper">
      <?php require_once("menu.php"); ?>
      <!-- partial -->
      <div class="main-panel">
        <form method="post" action="/configuracoes-transcoder" name="transcoder" style="padding:0px; margin:0px">
        <div class="content-wrapper">
          <div id="local-status-acoes"><?php echo $_SESSION['status_acao'];unset($_SESSION['status_acao']); ?></div>
          <div class="row">            

            <div class="col-lg-12">
              <div class="card">
                  <div class="card-header">
                    <header>Transcoder Multi Bitrate</header>
                  </div>
                <div class="card-body">
                    <?php if($dados_stm["transcoder"] == 'sim' && $dados_stm["transcoder_instalado"] == 'nao') { ?>
                      <center><br><br><button type="button" class="btn btn-info" onClick="window.location = '/configuracoes-transcoder/instalar';">Instalar</button><br><br></center>
                      <?php } ?>
                      <?php if($dados_stm["transcoder"] == 'sim' && $dados_stm["transcoder_instalado"] == 'sim') { ?>
                        <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                                <?php if($dados_stm["bitrate"] > 2040) { ?>
                                  <tr>
                                    <td width="45" height="25" align="center"><input type="checkbox" name="qualidades[]" value="1080p" <?php if(strpos($dados_stm["transcoder_qualidades"], '1080p') !== false) {echo 'checked="checked"';} ?> /></td>
                                    <td align="left">1080p (+2048Kbps @ 1920 x 1080)</td>
                                  </tr>
                                  <?php } ?>
                                  <?php if($dados_stm["bitrate"] > 1020) { ?>
                                  <tr>
                                    <td width="45" height="25" align="center"><input type="checkbox" name="qualidades[]" value="720p" <?php if(strpos($dados_stm["transcoder_qualidades"], '720p') !== false) {echo 'checked="checked"';} ?> /></td>
                                    <td align="left">720p (1396Kbps @ 1280 x 720)</td>
                                  </tr>
                                  <?php } ?>
                                  <tr>
                                    <td height="25" align="center"><input type="checkbox" name="qualidades[]" value="360p" <?php if(strpos($dados_stm["transcoder_qualidades"], '360p') !== false) {echo 'checked="checked"';} ?> /></td>
                                    <td align="left">360p (1024Kbps @ 640 x 360)</td>
                                 </tr>
                                  <tr>
                                    <td height="25" align="center"><input type="checkbox" name="qualidades[]" value="240p" <?php if(strpos($dados_stm["transcoder_qualidades"], '240p') !== false) {echo 'checked="checked"';} ?> /></td>
                                    <td align="left">240p (350 @ 360 x 240)</td>
                                  </tr>
                                  <tr>
                                    <td height="25" align="center"><input type="checkbox" name="qualidades[]" value="160p" <?php if(strpos($dados_stm["transcoder_qualidades"], '160p') !== false) {echo 'checked="checked"';} ?> /></td>
                                    <td align="left">160p (200Kbps @ 284 x 160)</td>
                                 </tr>
                                 <tr>
                                    <td height="50" colspan="2" align="right"><input type="hidden" name="alterar" value="sim" /><button type="button" class="btn btn-info" onClick="document.transcoder.submit();"><?php echo $lang['lang_botao_titulo_alterar_config']; ?></button></td>
                                  </tr>
                                </table>
                        <?php } ?>
                </div>
              </div>
            </div>

          </div>
        </div>
      </form>
      </div>
      <!-- modal -->
      <div class="modal fade" id="avisos" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?php echo $lang['lang_info_pagina_informacoes_tab_avisos']; ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                </div>
                <div class="modal-body" id="avisos-conteudo"><img src="/img/ajax-loader.gif" align="center" /></div>
            </div>
        </div>
        </div>
                
        <div class="modal fade" id="log-sistema" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body" id="log-sistema-conteudo" style="text-align:center"><img src="/img/ajax-loader.gif" /></div>
            </div>
        </div>
      </div>
    </div>
  </div>
  <script src="/inc/vendor.bundle.base.js"></script>
  <script src="/inc/vendor.bundle.addons.js"></script>
  <script src="/inc/theme.js"></script>
  <script>
  status_streaming('<?php echo $login_code; ?>');
  setInterval("status_streaming('<?php echo $login_code; ?>')",60000);
  </script>
</body>
</html>