﻿<?xml version="1.0" encoding="utf-8"?>
<HmsTranscodingConfig version="2.25">
  <TranscoderList>
    <Transcoder>
      <Name>HMSMPEG</Name>
      <Path>hmsmpeg.exe</Path>
      <HomePage>http://www.ffmpeg.org/</HomePage>
      <Download></Download>
    </Transcoder>
    <Transcoder>
      <Name>HmsMPEG</Name>
      <Path>Hmsmpeg.exe</Path>
      <HomePage>http://www.ffmpeg.org/</HomePage>
      <Download></Download>
    </Transcoder>
    <Transcoder>
      <Name>hmsMPEG</Name>
      <Path>hmsmpeg.exe</Path>
      <HomePage>http://www.ffmpeg.org/</HomePage>
      <Download></Download>
    </Transcoder>
  </TranscoderList>
  <TranscodingProfileList>
    <Profile>
      <TranscoderName>HMSMPEG</TranscoderName>
      <TranscodingCondition></TranscodingCondition>
      <TranscodingConditionSyntaxType>PascalScript</TranscodingConditionSyntaxType>
      <TranscodingComment></TranscodingComment>
      <TranscodingFolder>Транскодирование для интернет медиа-ресурсов</TranscodingFolder>
      <TranscodingMediaType>3</TranscodingMediaType>
      <TranscodingMimeType></TranscodingMimeType>
      <TranscodingMimeTypeScript>cfgTranscodingVideoMimeType</TranscodingMimeTypeScript>
      <TranscodingMimeTypeSyntaxType>PascalScript</TranscodingMimeTypeSyntaxType>
      <TranscodingMode>1</TranscodingMode>
      <TranscodingParams>// Версия 2.02 (HMS pipe)
// Профиль берет ссылку на медиаресурс через скрипт получения ссылки,
// используя: HmsGetItemProperty(mpiMediaResourceLink) и получает поток
// напрямую, минуя встроенные в livestreamer плагины, используя конструкцию:
// protocol://path [key=value]
// Например:
// livestreamer "rtmp://streaming.server.net/playpath live=1 swfVfy=http://server.net/flashplayer.swf"
// livestreamer hds://streaming.server.net/playpath/manifest.f4m
// За определение типа потока отвечает функция GetStreamType
// 04.06 - В код добавлены параметры командной строки на будущее
// Добавлен параметр --default-stream на случай пустой переменной csQuality
//
// Stream transport options
// --hds-live-edge SECONDS
// --hds-segment-attempts ATTEMPTS
// --hds-segment-threads THREADS
// --hds-segment-timeout TIMEOUT
// --hds-timeout TIMEOUT
// --hls-live-edge SEGMENTS
// --hls-segment-attempts ATTEMPTS
// --hls-segment-threads THREADS
// --hls-segment-timeout TIMEOUT
// --hls-timeout TIMEOUT
// --http-stream-timeout TIMEOUT
// --ringbuffer-size SIZE
//
// --rtmp-proxy PROXY, --rtmpdump-proxy PROXY
// --rtmp-rtmpdump FILENAME, --rtmpdump FILENAME, -r FILENAME
// --rtmp-timeout TIMEOUT
// --stream-segment-attempts ATTEMPTS
// --stream-segment-threads THREADS
// --stream-segment-timeout TIMEOUT
// --stream-timeout TIMEOUT
// HTTP PROXY
// --http-proxy HTTP_PROXY
// --https-proxy HTTPS_PROXY
// --http-cookie KEY=VALUE
// --http-header KEY=VALUE
// --http-query-param KEY=VALUE
// --http-ignore-env
// --http-no-ssl-verify
// --http-ssl-cert FILENAME
// --http-ssl-cert-crt-key CRT_FILENAME KEY_FILENAME
// --http-timeout TIMEOUT
// Plugin options
// --twitch-oauth-token TOKEN
// --twitch-oauth-authenticate
// --twitch-cookie COOKIES
// --ustream-password PASSWORD
// --crunchyroll-username USERNAME
// --crunchyroll-password [PASSWORD]
// --crunchyroll-purge-credentials
// --livestation-email EMAIL
// --livestation-password PASSWORD
// Полное описание тут: http://docs.livestreamer.io/cli.html
const
  csDumpParams = &apos;%s "%s" --default-stream "best" --hls-segment-threads 3 --hls-segment-attempts 1 -l %s -f -o "%s"&apos;;
  csQuality = "720p,480p,best";         //Предпочитаемое качество потока
  cbDebug = False;                      //Активация режима отладки
  csPathToLog = &apos;d:\tmp\livestream-ffmpeg-stream.log&apos;; //Путь в файлу для записи отладочной информации
                                        //его содержимое выслать автору
  
procedure DoDebug(const strToLog: string);
var 
  sCurrLog: String;
begin
  if cbDebug then
  begin
    if FileExists(csPathToLog) then sCurrLog := HmsStringFromFile(csPathToLog); 
    HmsStringToFile(sCurrLog+#13+VarToStr(Now)+&apos; &apos;+strToLog, csPathToLog);
    HmsLogMessage(1, strToLog);
  end;
end;

// На вход функция принимает декодированную ссылку, возвращает тип потока
function GetStreamType(const aInputLink: String): String; 
var
  sInputFileName: String;
begin
  DoDebug("Getting stream type");
  Result := &apos;&apos;;
  if EndPos(aInputLink,&apos;.m3u8&apos;) then Result := &apos;hls://&apos;
  else if EndPos(aInputLink,&apos;.f4m&apos;) then Result := &apos;hds://&apos;
end;

// На вход функция принимает ссылку и тип потока, возвращает True или False, а так же имя файла pipe
function ExecuteLivestreamer(const aCommandLine, aLinkType: string; var aInputFileName: string): boolean;
var
  sDumpParams, sReadPipeName, sWritePipeName, sDebugKey: string;
  bTest: Boolean;
begin
  Result := False;
  if (HmsCreateDualPipe(sReadPipeName, sWritePipeName)) then
    begin
      DoDebug("Executing livestreamer stage, creating pipes: for WRITE "+sWritePipeName+" and for READ "+sReadPipeName);
      bTest := HmsFileLocked(sWritePipeName);
      DoDebug("Is pipe "+sWritePipeName+" writable: "+Str(bTest));
      if bTest then
        Begin
          if cbDebug then sDebugKey := &apos;debug&apos;
          else sDebugKey := &apos;none&apos;;
          sDumpParams := Format(&apos;"%s" "%s" --default-stream "best" --hls-segment-threads 3 --hls-segment-attempts 1 -l %s -f -o "%s"&apos;, [aLinkType+aCommandLine, csQuality, sDebugKey, sWritePipeName]);
          DoDebug("Livestreamer exec params: "+sDumpParams);
          Result := HmsTranscodingExecute(&apos;LSTREAMER&apos;, sDumpParams, False);
          DoDebug("Result of execution: "+Str(Result));
          if Result then
            aInputFileName := sReadPipeName
        end;
    end
end;

// На вход принимает ссылку, возвращает True, если livestreamer может обработать ссылку или False, если не может
function CheckForValidLink(const aInputFileName: string) : boolean;

begin
  Result := False;
  //Result := HmsTranscodingExecute(&apos;LSTREAMER&apos;,&apos;--can-handle-url &apos;+InputFileName);
  DoDebug("Is link valid: "+str(Result));
end;

var 
  bSuccess, bLinkValid: Boolean;
  sLinkType, sFileType, sInputFileName, sRtmpServer, sRtmpFile, sTranscodingParams: string;  
begin
  TranscodingResult := False;
  DoDebug("Обработка для профиля устройства: "+Str(cfgDeviceType));
  if HmsGetStreamCount = 0 then  
    HmsRetrieveProperties;
  InputFileName := Trim(HmsGetItemProperty(mpiMediaResourceLink));
  if InputFileName = &apos;&apos; then InputFileName := HmsGetItemProperty(mpiFilePath);
  DoDebug("URI ресурса: "+InputFileName);
  sLinkType := GetStreamType(InputFileName);
  
  if sLinkType &lt;&gt; &apos;&apos; then
    begin
      bSuccess := ExecuteLivestreamer(InputFileName, sLinkType, sInputFileName);
      DoDebug("Livestreamer part worked, going to transcode pipe: "+sInputFileName);
    end
  else
    begin
      bSuccess := False;
      DoDebug("Livestreamer didn&apos;t found any valid stream on URL: "+InputFileName);
    end;  
  // Берем базовые параметры транскодирования из профиля Фильмы (основной)
  sTranscodingParams := HmsTranscodingProfileParams(&apos;Фильмы (основной)&apos;);
  if bSuccess then begin
    mpInternetItem := False;
    sTranscodingParams := ReplaceStr(sTranscodingParams, &apos;&lt;HMSMPEG&gt; &apos;, &apos;&apos;);
  //end else
  //  begin
  //    sInputFileName := InputFileName;
  //    DoDebug("Transcoding without livestreamer")
    end;
  sTranscodingParams := sTranscodingParams + &apos; -strict experimental "&lt;OUTPUT FILE&gt;"&apos;;
  DoDebug("Starting transcode with commandline: "+sTranscodingParams);
  TranscodingResult := HmsTranscodingExecute(&apos;HMSMPEG&apos;, sTranscodingParams, True, sInputFileName, OutputFileName);
  DoDebug("Finishing transcode with result: "+Str(TranscodingResult));  
end.</TranscodingParams>
      <TranscodingParamsSyntaxType>PascalScript</TranscodingParamsSyntaxType>
      <TranscodingProfile>Фильмы - LIVESTREAM - FFMPEG - STREAM</TranscodingProfile>
      <TranscodingProfileActive>-1</TranscodingProfileActive>
      <TranscodingProfilePriority>53</TranscodingProfilePriority>
      <TranscodingProfileUuid>ef6d6aeb-f4d1-4f52-b3c0-ee64a7562ef3</TranscodingProfileUuid>
    </Profile>
  </TranscodingProfileList>
</HmsTranscodingConfig>
