2014-10-15 20:26:39 -07:00
using MediaBrowser.Common.IO ;
2014-10-12 10:31:41 -07:00
using MediaBrowser.Common.Net ;
using MediaBrowser.Controller.Configuration ;
2015-01-19 22:19:13 -07:00
using MediaBrowser.Controller.Devices ;
2015-02-28 11:47:05 -07:00
using MediaBrowser.Controller.Diagnostics ;
2014-10-12 10:31:41 -07:00
using MediaBrowser.Controller.Dlna ;
using MediaBrowser.Controller.Library ;
using MediaBrowser.Controller.LiveTv ;
using MediaBrowser.Controller.MediaEncoding ;
2014-10-15 20:26:39 -07:00
using MediaBrowser.Controller.Net ;
2014-10-12 10:31:41 -07:00
using MediaBrowser.Model.IO ;
using ServiceStack ;
using System ;
using System.Collections.Generic ;
using System.Globalization ;
2014-10-15 20:26:39 -07:00
using System.IO ;
using System.Linq ;
using System.Security ;
2014-10-12 10:31:41 -07:00
using System.Text ;
using System.Threading ;
using System.Threading.Tasks ;
2014-12-26 10:45:06 -07:00
using MimeTypes = MediaBrowser . Model . Net . MimeTypes ;
2014-10-12 10:31:41 -07:00
namespace MediaBrowser.Api.Playback.Hls
{
/// <summary>
/// Options is needed for chromecast. Threw Head in there since it's related
/// </summary>
[Route("/Videos/{Id}/master.mpd", "GET", Summary = "Gets a video stream using Mpeg dash.")]
[Route("/Videos/{Id}/master.mpd", "HEAD", Summary = "Gets a video stream using Mpeg dash.")]
public class GetMasterManifest : VideoStreamRequest
{
public bool EnableAdaptiveBitrateStreaming { get ; set ; }
public GetMasterManifest ( )
{
EnableAdaptiveBitrateStreaming = true ;
}
}
2015-03-09 19:37:24 -07:00
[Route("/Videos/{Id}/dash/audio/{SegmentId}.m4s", "GET")]
[Route("/Videos/{Id}/dash/video/{SegmentId}.m4s", "GET")]
2014-10-12 10:31:41 -07:00
public class GetDashSegment : VideoStreamRequest
{
/// <summary>
/// Gets or sets the segment id.
/// </summary>
/// <value>The segment id.</value>
public string SegmentId { get ; set ; }
}
2014-10-14 17:04:44 -07:00
2014-10-12 10:31:41 -07:00
public class MpegDashService : BaseHlsService
{
2015-03-07 15:43:53 -07:00
public MpegDashService ( IServerConfigurationManager serverConfig , IUserManager userManager , ILibraryManager libraryManager , IIsoManager isoManager , IMediaEncoder mediaEncoder , IFileSystem fileSystem , ILiveTvManager liveTvManager , IDlnaManager dlnaManager , ISubtitleEncoder subtitleEncoder , IDeviceManager deviceManager , IProcessManager processManager , IMediaSourceManager mediaSourceManager , INetworkManager networkManager ) : base ( serverConfig , userManager , libraryManager , isoManager , mediaEncoder , fileSystem , liveTvManager , dlnaManager , subtitleEncoder , deviceManager , processManager , mediaSourceManager )
2014-10-12 10:31:41 -07:00
{
NetworkManager = networkManager ;
}
2015-01-19 22:19:13 -07:00
protected INetworkManager NetworkManager { get ; private set ; }
2014-10-12 10:31:41 -07:00
public object Get ( GetMasterManifest request )
{
var result = GetAsync ( request , "GET" ) . Result ;
return result ;
}
public object Head ( GetMasterManifest request )
{
var result = GetAsync ( request , "HEAD" ) . Result ;
return result ;
}
private async Task < object > GetAsync ( GetMasterManifest request , string method )
{
if ( string . Equals ( request . AudioCodec , "copy" , StringComparison . OrdinalIgnoreCase ) )
{
throw new ArgumentException ( "Audio codec copy is not allowed here." ) ;
}
if ( string . Equals ( request . VideoCodec , "copy" , StringComparison . OrdinalIgnoreCase ) )
{
throw new ArgumentException ( "Video codec copy is not allowed here." ) ;
}
if ( string . IsNullOrEmpty ( request . MediaSourceId ) )
{
throw new ArgumentException ( "MediaSourceId is required" ) ;
}
var state = await GetState ( request , CancellationToken . None ) . ConfigureAwait ( false ) ;
var playlistText = string . Empty ;
if ( string . Equals ( method , "GET" , StringComparison . OrdinalIgnoreCase ) )
{
playlistText = GetManifestText ( state ) ;
}
2014-12-26 10:45:06 -07:00
return ResultFactory . GetResult ( playlistText , MimeTypes . GetMimeType ( "playlist.mpd" ) , new Dictionary < string , string > ( ) ) ;
2014-10-12 10:31:41 -07:00
}
private string GetManifestText ( StreamState state )
{
var builder = new StringBuilder ( ) ;
2014-10-14 21:11:40 -07:00
var time = TimeSpan . FromTicks ( state . RunTimeTicks . Value ) ;
var duration = "PT" + time . Hours . ToString ( "00" , UsCulture ) + "H" + time . Minutes . ToString ( "00" , UsCulture ) + "M" + time . Seconds . ToString ( "00" , UsCulture ) + ".00S" ;
2014-10-12 10:31:41 -07:00
2014-10-14 17:04:44 -07:00
builder . Append ( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ) ;
2014-10-15 20:26:39 -07:00
2014-10-12 10:31:41 -07:00
builder . AppendFormat (
2015-03-09 19:37:24 -07:00
"<MPD xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:mpeg:dash:schema:mpd:2011\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011 http://standards.iso.org/ittf/PubliclyAvailableStandards/MPEG-DASH_schema_files/DASH-MPD.xsd\" profiles=\"urn:mpeg:dash:profile:isoff-live:2011\" type=\"static\" mediaPresentationDuration=\"{0}\" minBufferTime=\"PT5.0S\">" ,
duration ) ;
2014-10-12 10:31:41 -07:00
2015-03-09 19:37:24 -07:00
builder . Append ( "<ProgramInformation>" ) ;
2014-10-12 10:31:41 -07:00
builder . Append ( "</ProgramInformation>" ) ;
2015-03-09 19:37:24 -07:00
builder . Append ( "<Period start=\"PT0S\">" ) ;
builder . Append ( GetVideoAdaptationSet ( state ) ) ;
builder . Append ( GetAudioAdaptationSet ( state ) ) ;
builder . Append ( "</Period>" ) ;
2014-10-12 10:31:41 -07:00
2015-03-09 19:37:24 -07:00
builder . Append ( "</MPD>" ) ;
2014-10-12 10:31:41 -07:00
2015-03-09 19:37:24 -07:00
return builder . ToString ( ) ;
}
2014-10-14 17:04:44 -07:00
2015-03-09 19:37:24 -07:00
private string GetVideoAdaptationSet ( StreamState state )
{
var builder = new StringBuilder ( ) ;
2014-10-14 17:04:44 -07:00
2015-03-09 19:37:24 -07:00
builder . Append ( "<AdaptationSet id=\"video\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">" ) ;
builder . Append ( GetVideoRepresentationOpenElement ( state ) ) ;
2014-10-12 10:31:41 -07:00
2015-03-09 19:37:24 -07:00
AppendSegmentList ( state , builder , "video" ) ;
2014-10-12 10:31:41 -07:00
builder . Append ( "</Representation>" ) ;
builder . Append ( "</AdaptationSet>" ) ;
2015-03-09 19:37:24 -07:00
return builder . ToString ( ) ;
}
private string GetAudioAdaptationSet ( StreamState state )
{
var builder = new StringBuilder ( ) ;
2014-10-12 10:31:41 -07:00
2015-03-09 19:37:24 -07:00
builder . Append ( "<AdaptationSet id=\"audio\" segmentAlignment=\"true\" bitstreamSwitching=\"true\">" ) ;
builder . Append ( GetAudioRepresentationOpenElement ( state ) ) ;
builder . Append ( "<AudioChannelConfiguration schemeIdUri=\"urn:mpeg:dash:23003:3:audio_channel_configuration:2011\" value=\"6\" />" ) ;
AppendSegmentList ( state , builder , "audio" ) ;
builder . Append ( "</Representation>" ) ;
builder . Append ( "</AdaptationSet>" ) ;
2014-10-12 10:31:41 -07:00
return builder . ToString ( ) ;
}
2015-03-09 19:37:24 -07:00
private string GetVideoRepresentationOpenElement ( StreamState state )
2014-10-12 10:31:41 -07:00
{
2015-03-09 19:37:24 -07:00
var codecs = GetVideoCodecDescriptor ( state ) ;
2014-10-14 17:04:44 -07:00
2015-03-09 19:37:24 -07:00
var mime = "video/mp4" ;
2014-10-15 20:26:39 -07:00
2015-03-09 19:37:24 -07:00
var xml = "<Representation id=\"0\" mimeType=\"" + mime + "\" codecs=\"" + codecs + "\"" ;
2014-10-14 17:04:44 -07:00
if ( state . OutputWidth . HasValue )
{
xml + = " width=\"" + state . OutputWidth . Value . ToString ( UsCulture ) + "\"" ;
}
if ( state . OutputHeight . HasValue )
{
xml + = " height=\"" + state . OutputHeight . Value . ToString ( UsCulture ) + "\"" ;
}
2015-03-09 19:37:24 -07:00
if ( state . OutputVideoBitrate . HasValue )
2014-10-14 17:04:44 -07:00
{
2015-03-09 19:37:24 -07:00
xml + = " bandwidth=\"" + state . OutputVideoBitrate . Value . ToString ( UsCulture ) + "\"" ;
2014-10-14 17:04:44 -07:00
}
2015-03-09 19:37:24 -07:00
xml + = ">" ;
return xml ;
}
private string GetAudioRepresentationOpenElement ( StreamState state )
{
var codecs = GetAudioCodecDescriptor ( state ) ;
var mime = "audio/mp4" ;
var xml = "<Representation id=\"1\" mimeType=\"" + mime + "\" codecs=\"" + codecs + "\"" ;
if ( state . OutputAudioSampleRate . HasValue )
{
xml + = " audioSamplingRate=\"" + state . OutputAudioSampleRate . Value . ToString ( UsCulture ) + "\"" ;
}
if ( state . OutputAudioBitrate . HasValue )
2014-10-14 17:04:44 -07:00
{
2015-03-09 19:37:24 -07:00
xml + = " bandwidth=\"" + state . OutputAudioBitrate . Value . ToString ( UsCulture ) + "\"" ;
2014-10-14 17:04:44 -07:00
}
xml + = ">" ;
return xml ;
}
private string GetVideoCodecDescriptor ( StreamState state )
{
// https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html
2014-10-15 20:26:39 -07:00
// http://www.chipwreck.de/blog/2010/02/25/html-5-video-tag-and-attributes/
2014-10-14 17:04:44 -07:00
var level = state . TargetVideoLevel ? ? 0 ;
var profile = state . TargetVideoProfile ? ? string . Empty ;
if ( profile . IndexOf ( "high" , StringComparison . OrdinalIgnoreCase ) ! = - 1 )
{
if ( level > = 4.1 )
{
return "avc1.640028" ;
}
if ( level > = 4 )
{
return "avc1.640028" ;
}
return "avc1.64001f" ;
}
if ( profile . IndexOf ( "main" , StringComparison . OrdinalIgnoreCase ) ! = - 1 )
{
if ( level > = 4 )
{
return "avc1.4d0028" ;
}
if ( level > = 3.1 )
{
return "avc1.4d001f" ;
}
return "avc1.4d001e" ;
}
if ( level > = 3.1 )
{
return "avc1.42001f" ;
}
2014-10-15 20:26:39 -07:00
return "avc1.42E01E" ;
2014-10-14 17:04:44 -07:00
}
private string GetAudioCodecDescriptor ( StreamState state )
{
// https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/FrequentlyAskedQuestions/FrequentlyAskedQuestions.html
if ( string . Equals ( state . OutputAudioCodec , "mp3" , StringComparison . OrdinalIgnoreCase ) )
{
return "mp4a.40.34" ;
}
// AAC 5ch
if ( state . OutputAudioChannels . HasValue & & state . OutputAudioChannels . Value > = 5 )
{
return "mp4a.40.5" ;
}
// AAC 2ch
return "mp4a.40.2" ;
2014-10-12 10:31:41 -07:00
}
public object Get ( GetDashSegment request )
{
2014-10-15 20:26:39 -07:00
return GetDynamicSegment ( request , request . SegmentId ) . Result ;
2014-10-12 10:31:41 -07:00
}
2015-03-09 19:37:24 -07:00
private void AppendSegmentList ( StreamState state , StringBuilder builder , string type )
2014-10-12 10:31:41 -07:00
{
2014-10-15 20:26:39 -07:00
var extension = GetSegmentFileExtension ( state ) ;
2014-10-12 10:31:41 -07:00
var seconds = TimeSpan . FromTicks ( state . RunTimeTicks ? ? 0 ) . TotalSeconds ;
var queryStringIndex = Request . RawUrl . IndexOf ( '?' ) ;
var queryString = queryStringIndex = = - 1 ? string . Empty : Request . RawUrl . Substring ( queryStringIndex ) ;
var index = 0 ;
2015-03-09 19:37:24 -07:00
builder . Append ( "<SegmentList timescale=\"1000000\" duration=\"5000000\" startNumber=\"1\">" ) ;
2014-10-15 20:26:39 -07:00
2014-10-12 10:31:41 -07:00
while ( seconds > 0 )
{
2015-03-09 19:37:24 -07:00
var segmentUrl = string . Format ( "dash/{3}/{0}{1}{2}" ,
2014-10-15 20:26:39 -07:00
index . ToString ( UsCulture ) ,
extension ,
2015-03-09 19:37:24 -07:00
SecurityElement . Escape ( queryString ) ,
type ) ;
2014-10-14 21:11:40 -07:00
2014-10-15 20:26:39 -07:00
if ( index = = 0 )
{
builder . AppendFormat ( "<Initialization sourceURL=\"{0}\"/>" , segmentUrl ) ;
}
else
{
builder . AppendFormat ( "<SegmentURL media=\"{0}\"/>" , segmentUrl ) ;
}
2014-10-12 10:31:41 -07:00
seconds - = state . SegmentLength ;
index + + ;
}
builder . Append ( "</SegmentList>" ) ;
}
2014-10-15 20:26:39 -07:00
private async Task < object > GetDynamicSegment ( VideoStreamRequest request , string segmentId )
{
if ( ( request . StartTimeTicks ? ? 0 ) > 0 )
{
throw new ArgumentException ( "StartTimeTicks is not allowed." ) ;
}
var cancellationTokenSource = new CancellationTokenSource ( ) ;
var cancellationToken = cancellationTokenSource . Token ;
var index = int . Parse ( segmentId , NumberStyles . Integer , UsCulture ) ;
var state = await GetState ( request , cancellationToken ) . ConfigureAwait ( false ) ;
2015-03-09 19:37:24 -07:00
var playlistPath = Path . ChangeExtension ( state . OutputFilePath , ".mpd" ) ;
2014-10-15 20:26:39 -07:00
var segmentExtension = GetSegmentFileExtension ( state ) ;
var segmentPath = GetSegmentPath ( playlistPath , segmentExtension , index ) ;
var segmentLength = state . SegmentLength ;
TranscodingJob job = null ;
if ( File . Exists ( segmentPath ) )
{
2015-03-09 19:37:24 -07:00
job = ApiEntryPoint . Instance . GetTranscodingJob ( playlistPath , TranscodingJobType ) ;
2014-10-15 20:26:39 -07:00
return await GetSegmentResult ( playlistPath , segmentPath , index , segmentLength , job , cancellationToken ) . ConfigureAwait ( false ) ;
}
await ApiEntryPoint . Instance . TranscodingStartLock . WaitAsync ( cancellationTokenSource . Token ) . ConfigureAwait ( false ) ;
try
{
if ( File . Exists ( segmentPath ) )
{
2015-03-09 19:37:24 -07:00
job = ApiEntryPoint . Instance . GetTranscodingJob ( playlistPath , TranscodingJobType ) ;
2014-10-15 20:26:39 -07:00
return await GetSegmentResult ( playlistPath , segmentPath , index , segmentLength , job , cancellationToken ) . ConfigureAwait ( false ) ;
}
else
{
var currentTranscodingIndex = GetCurrentTranscodingIndex ( playlistPath , segmentExtension ) ;
if ( currentTranscodingIndex = = null | | index < currentTranscodingIndex . Value | | ( index - currentTranscodingIndex . Value ) > 4 )
{
// If the playlist doesn't already exist, startup ffmpeg
try
{
ApiEntryPoint . Instance . KillTranscodingJobs ( j = > j . Type = = TranscodingJobType & & string . Equals ( j . DeviceId , request . DeviceId , StringComparison . OrdinalIgnoreCase ) , p = > ! string . Equals ( p , playlistPath , StringComparison . OrdinalIgnoreCase ) ) ;
if ( currentTranscodingIndex . HasValue )
{
DeleteLastFile ( playlistPath , segmentExtension , 0 ) ;
}
var startSeconds = index * state . SegmentLength ;
request . StartTimeTicks = TimeSpan . FromSeconds ( startSeconds ) . Ticks ;
job = await StartFfMpeg ( state , playlistPath , cancellationTokenSource , Path . GetDirectoryName ( playlistPath ) ) . ConfigureAwait ( false ) ;
}
catch
{
state . Dispose ( ) ;
throw ;
}
await WaitForMinimumSegmentCount ( playlistPath , 2 , cancellationTokenSource . Token ) . ConfigureAwait ( false ) ;
}
}
}
finally
{
ApiEntryPoint . Instance . TranscodingStartLock . Release ( ) ;
}
Logger . Info ( "waiting for {0}" , segmentPath ) ;
while ( ! File . Exists ( segmentPath ) )
{
await Task . Delay ( 50 , cancellationToken ) . ConfigureAwait ( false ) ;
}
Logger . Info ( "returning {0}" , segmentPath ) ;
job = job ? ? ApiEntryPoint . Instance . GetTranscodingJob ( playlistPath , TranscodingJobType ) ;
return await GetSegmentResult ( playlistPath , segmentPath , index , segmentLength , job , cancellationToken ) . ConfigureAwait ( false ) ;
}
private async Task < object > GetSegmentResult ( string playlistPath ,
string segmentPath ,
int segmentIndex ,
int segmentLength ,
TranscodingJob transcodingJob ,
CancellationToken cancellationToken )
{
// If all transcoding has completed, just return immediately
if ( ! IsTranscoding ( playlistPath ) )
{
return GetSegmentResult ( segmentPath , segmentIndex , segmentLength , transcodingJob ) ;
}
var segmentFilename = Path . GetFileName ( segmentPath ) ;
using ( var fileStream = FileSystem . GetFileStream ( playlistPath , FileMode . Open , FileAccess . Read , FileShare . ReadWrite , true ) )
{
using ( var reader = new StreamReader ( fileStream ) )
{
var text = await reader . ReadToEndAsync ( ) . ConfigureAwait ( false ) ;
// If it appears in the playlist, it's done
if ( text . IndexOf ( segmentFilename , StringComparison . OrdinalIgnoreCase ) ! = - 1 )
{
return GetSegmentResult ( segmentPath , segmentIndex , segmentLength , transcodingJob ) ;
}
}
}
// if a different file is encoding, it's done
//var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
//if (currentTranscodingIndex > segmentIndex)
//{
//return GetSegmentResult(segmentPath, segmentIndex);
//}
// Wait for the file to stop being written to, then stream it
var length = new FileInfo ( segmentPath ) . Length ;
var eofCount = 0 ;
while ( eofCount < 10 )
{
var info = new FileInfo ( segmentPath ) ;
if ( ! info . Exists )
{
break ;
}
var newLength = info . Length ;
if ( newLength = = length )
{
eofCount + + ;
}
else
{
eofCount = 0 ;
}
length = newLength ;
await Task . Delay ( 100 , cancellationToken ) . ConfigureAwait ( false ) ;
}
return GetSegmentResult ( segmentPath , segmentIndex , segmentLength , transcodingJob ) ;
}
private object GetSegmentResult ( string segmentPath , int index , int segmentLength , TranscodingJob transcodingJob )
{
var segmentEndingSeconds = ( 1 + index ) * segmentLength ;
var segmentEndingPositionTicks = TimeSpan . FromSeconds ( segmentEndingSeconds ) . Ticks ;
return ResultFactory . GetStaticFileResult ( Request , new StaticFileResultOptions
{
Path = segmentPath ,
FileShare = FileShare . ReadWrite ,
OnComplete = ( ) = >
{
if ( transcodingJob ! = null )
{
transcodingJob . DownloadPositionTicks = Math . Max ( transcodingJob . DownloadPositionTicks ? ? segmentEndingPositionTicks , segmentEndingPositionTicks ) ;
}
}
} ) ;
}
private bool IsTranscoding ( string playlistPath )
{
var job = ApiEntryPoint . Instance . GetTranscodingJob ( playlistPath , TranscodingJobType ) ;
return job ! = null & & ! job . HasExited ;
}
public int? GetCurrentTranscodingIndex ( string playlist , string segmentExtension )
{
var file = GetLastTranscodingFile ( playlist , segmentExtension , FileSystem ) ;
if ( file = = null )
{
return null ;
}
var playlistFilename = Path . GetFileNameWithoutExtension ( playlist ) ;
var indexString = Path . GetFileNameWithoutExtension ( file . Name ) . Substring ( playlistFilename . Length ) ;
return int . Parse ( indexString , NumberStyles . Integer , UsCulture ) ;
}
private void DeleteLastFile ( string path , string segmentExtension , int retryCount )
{
if ( retryCount > = 5 )
{
return ;
}
var file = GetLastTranscodingFile ( path , segmentExtension , FileSystem ) ;
if ( file ! = null )
{
try
{
2015-01-12 20:46:44 -07:00
FileSystem . DeleteFile ( file . FullName ) ;
2014-10-15 20:26:39 -07:00
}
catch ( IOException ex )
{
Logger . ErrorException ( "Error deleting partial stream file(s) {0}" , ex , file . FullName ) ;
Thread . Sleep ( 100 ) ;
DeleteLastFile ( path , segmentExtension , retryCount + 1 ) ;
}
catch ( Exception ex )
{
Logger . ErrorException ( "Error deleting partial stream file(s) {0}" , ex , file . FullName ) ;
}
}
}
private static FileInfo GetLastTranscodingFile ( string playlist , string segmentExtension , IFileSystem fileSystem )
{
var folder = Path . GetDirectoryName ( playlist ) ;
try
{
return new DirectoryInfo ( folder )
. EnumerateFiles ( "*" , SearchOption . TopDirectoryOnly )
. Where ( i = > string . Equals ( i . Extension , segmentExtension , StringComparison . OrdinalIgnoreCase ) )
. OrderByDescending ( fileSystem . GetLastWriteTimeUtc )
. FirstOrDefault ( ) ;
}
catch ( DirectoryNotFoundException )
{
return null ;
}
}
protected override int GetStartNumber ( StreamState state )
{
return GetStartNumber ( state . VideoRequest ) ;
}
private int GetStartNumber ( VideoStreamRequest request )
{
var segmentId = "0" ;
var segmentRequest = request as GetDynamicHlsVideoSegment ;
if ( segmentRequest ! = null )
{
segmentId = segmentRequest . SegmentId ;
}
return int . Parse ( segmentId , NumberStyles . Integer , UsCulture ) ;
}
private string GetSegmentPath ( string playlist , string segmentExtension , int index )
{
var folder = Path . GetDirectoryName ( playlist ) ;
var filename = Path . GetFileNameWithoutExtension ( playlist ) ;
return Path . Combine ( folder , filename + index . ToString ( "000" , UsCulture ) + segmentExtension ) ;
}
2014-10-12 10:31:41 -07:00
protected override string GetAudioArguments ( StreamState state )
{
var codec = state . OutputAudioCodec ;
if ( codec . Equals ( "copy" , StringComparison . OrdinalIgnoreCase ) )
{
return "-codec:a:0 copy" ;
}
var args = "-codec:a:0 " + codec ;
var channels = state . OutputAudioChannels ;
if ( channels . HasValue )
{
args + = " -ac " + channels . Value ;
}
var bitrate = state . OutputAudioBitrate ;
if ( bitrate . HasValue )
{
args + = " -ab " + bitrate . Value . ToString ( UsCulture ) ;
}
args + = " " + GetAudioFilterParam ( state , true ) ;
return args ;
}
protected override string GetVideoArguments ( StreamState state )
{
var codec = state . OutputVideoCodec ;
2014-12-26 10:45:06 -07:00
var args = "-codec:v:0 " + codec ;
if ( state . EnableMpegtsM2TsMode )
{
args + = " -mpegts_m2ts_mode 1" ;
}
2014-10-12 10:31:41 -07:00
// See if we can save come cpu cycles by avoiding encoding
if ( codec . Equals ( "copy" , StringComparison . OrdinalIgnoreCase ) )
{
2014-12-26 10:45:06 -07:00
return state . VideoStream ! = null & & IsH264 ( state . VideoStream ) ?
args + " -bsf:v h264_mp4toannexb" :
args ;
2014-10-12 10:31:41 -07:00
}
var keyFrameArg = string . Format ( " -force_key_frames expr:gte(t,n_forced*{0})" ,
state . SegmentLength . ToString ( UsCulture ) ) ;
var hasGraphicalSubs = state . SubtitleStream ! = null & & ! state . SubtitleStream . IsTextSubtitleStream ;
2014-12-26 10:45:06 -07:00
args + = " " + GetVideoQualityParam ( state , H264Encoder , true ) + keyFrameArg ;
2014-10-12 10:31:41 -07:00
2014-11-08 20:18:14 -07:00
args + = " -r 24 -g 24" ;
2014-10-12 10:31:41 -07:00
// Add resolution params, if specified
if ( ! hasGraphicalSubs )
{
args + = GetOutputSizeParam ( state , codec , false ) ;
}
// This is for internal graphical subs
if ( hasGraphicalSubs )
{
args + = GetGraphicalSubtitleParam ( state , codec ) ;
}
return args ;
}
protected override string GetCommandLineArguments ( string outputPath , string transcodingJobId , StreamState state , bool isEncoding )
{
2015-01-17 12:30:23 -07:00
// test url http://192.168.1.2:8096/videos/233e8905d559a8f230db9bffd2ac9d6d/master.mpd?mediasourceid=233e8905d559a8f230db9bffd2ac9d6d&videocodec=h264&audiocodec=aac&maxwidth=1280&videobitrate=500000&audiobitrate=128000&profile=baseline&level=3
2014-11-08 20:18:14 -07:00
// Good info on i-frames http://blog.streamroot.io/encode-multi-bitrate-videos-mpeg-dash-mse-based-media-players/
2014-10-12 10:31:41 -07:00
var threads = GetNumberOfThreads ( state , false ) ;
var inputModifier = GetInputModifier ( state ) ;
2015-03-09 19:37:24 -07:00
var args = string . Format ( "{0} {1} -map_metadata -1 -threads {2} {3} {4} -copyts {5} -f dash -use_template 0 -min_seg_duration 2000 \"{6}\"" ,
2014-10-12 10:31:41 -07:00
inputModifier ,
GetInputArgument ( transcodingJobId , state ) ,
threads ,
GetMapArgs ( state ) ,
GetVideoArguments ( state ) ,
GetAudioArguments ( state ) ,
2015-03-09 19:37:24 -07:00
outputPath
2014-10-12 10:31:41 -07:00
) . Trim ( ) ;
return args ;
}
/// <summary>
/// Gets the segment file extension.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
protected override string GetSegmentFileExtension ( StreamState state )
{
2015-03-09 19:37:24 -07:00
return ".m4s" ;
2014-10-12 10:31:41 -07:00
}
protected override TranscodingJobType TranscodingJobType
{
get
{
return TranscodingJobType . Dash ;
}
}
}
}