2013-11-01 15:59:42 +00:00
using MediaBrowser.Common.IO ;
2013-12-15 19:39:21 +00:00
using MediaBrowser.Controller.Configuration ;
2013-09-04 17:02:19 +00:00
using MediaBrowser.Controller.Dto ;
2013-02-27 23:33:40 +00:00
using MediaBrowser.Controller.Library ;
2013-12-21 18:37:34 +00:00
using MediaBrowser.Controller.LiveTv ;
2014-01-12 06:31:21 +00:00
using MediaBrowser.Controller.MediaInfo ;
2013-12-06 03:39:44 +00:00
using MediaBrowser.Controller.Persistence ;
2014-01-12 21:32:13 +00:00
using MediaBrowser.Model.Dto ;
2013-08-10 01:16:31 +00:00
using MediaBrowser.Model.IO ;
2013-12-07 15:52:38 +00:00
using ServiceStack ;
2013-07-02 18:24:29 +00:00
using System ;
2014-01-12 21:32:13 +00:00
using System.Collections.Generic ;
2014-01-13 05:41:00 +00:00
using System.IO ;
using System.Linq ;
2014-01-12 21:32:13 +00:00
using System.Text ;
using System.Threading ;
using System.Threading.Tasks ;
2013-02-27 23:33:40 +00:00
namespace MediaBrowser.Api.Playback.Hls
{
2013-04-29 16:01:23 +00:00
/// <summary>
/// Class GetHlsVideoStream
/// </summary>
2013-03-09 06:13:10 +00:00
[Route("/Videos/{Id}/stream.m3u8", "GET")]
2013-03-28 14:42:03 +00:00
[Api(Description = "Gets a video stream using HTTP live streaming.")]
2013-03-09 06:13:10 +00:00
public class GetHlsVideoStream : VideoStreamRequest
{
2013-09-06 17:27:06 +00:00
[ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? BaselineStreamAudioBitRate { get ; set ; }
2013-03-09 06:13:10 +00:00
2013-09-06 17:27:06 +00:00
[ApiMember(Name = "AppendBaselineStream", Description = "Optional. Whether or not to include a baseline audio-only stream in the master playlist.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool AppendBaselineStream { get ; set ; }
2013-09-19 20:03:14 +00:00
[ApiMember(Name = "TimeStampOffsetMs", Description = "Optional. Alter the timestamps in the playlist by a given amount, in ms. Default is 1000.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int TimeStampOffsetMs { get ; set ; }
2013-03-09 06:13:10 +00:00
}
2014-01-12 21:32:13 +00:00
[Route("/Videos/{Id}/master.m3u8", "GET")]
[Api(Description = "Gets a video stream using HTTP live streaming.")]
public class GetMasterHlsVideoStream : VideoStreamRequest
{
[ApiMember(Name = "BaselineStreamAudioBitRate", Description = "Optional. Specify the audio bitrate for the baseline stream.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? BaselineStreamAudioBitRate { get ; set ; }
[ApiMember(Name = "AppendBaselineStream", Description = "Optional. Whether or not to include a baseline audio-only stream in the master playlist.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool AppendBaselineStream { get ; set ; }
}
[Route("/Videos/{Id}/main.m3u8", "GET")]
[Api(Description = "Gets a video stream using HTTP live streaming.")]
public class GetMainHlsVideoStream : VideoStreamRequest
{
}
[Route("/Videos/{Id}/baseline.m3u8", "GET")]
[Api(Description = "Gets a video stream using HTTP live streaming.")]
public class GetBaselineHlsVideoStream : VideoStreamRequest
{
}
2014-01-13 05:41:00 +00:00
/// <summary>
/// Class GetHlsVideoSegment
/// </summary>
[Route("/Videos/{Id}/hls/{PlaylistId}/{SegmentId}.ts", "GET")]
[Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
public class GetHlsVideoSegment
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public string Id { get ; set ; }
public string PlaylistId { get ; set ; }
/// <summary>
/// Gets or sets the segment id.
/// </summary>
/// <value>The segment id.</value>
public string SegmentId { get ; set ; }
}
2013-04-29 16:01:23 +00:00
/// <summary>
/// Class VideoHlsService
/// </summary>
2013-02-27 23:33:40 +00:00
public class VideoHlsService : BaseHlsService
{
2013-12-21 18:37:34 +00:00
public VideoHlsService ( IServerConfigurationManager serverConfig , IUserManager userManager , ILibraryManager libraryManager , IIsoManager isoManager , IMediaEncoder mediaEncoder , IDtoService dtoService , IFileSystem fileSystem , IItemRepository itemRepository , ILiveTvManager liveTvManager )
: base ( serverConfig , userManager , libraryManager , isoManager , mediaEncoder , dtoService , fileSystem , itemRepository , liveTvManager )
2013-02-27 23:33:40 +00:00
{
}
2014-01-12 21:32:13 +00:00
public object Get ( GetMasterHlsVideoStream request )
{
var result = GetAsync ( request ) . Result ;
return result ;
}
public object Get ( GetMainHlsVideoStream request )
{
var result = GetPlaylistAsync ( request , "main" ) . Result ;
return result ;
}
public object Get ( GetBaselineHlsVideoStream request )
{
var result = GetPlaylistAsync ( request , "baseline" ) . Result ;
return result ;
}
2014-01-13 05:41:00 +00:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetHlsVideoSegment request )
{
var file = request . SegmentId + Path . GetExtension ( Request . PathInfo ) ;
file = Path . Combine ( ServerConfigurationManager . ApplicationPaths . TranscodingTempPath , file ) ;
OnBeginRequest ( request . PlaylistId ) ;
return ResultFactory . GetStaticFileResult ( Request , file ) ;
}
2014-01-12 21:32:13 +00:00
private async Task < object > GetPlaylistAsync ( VideoStreamRequest request , string name )
{
var state = await GetState ( request , CancellationToken . None ) . ConfigureAwait ( false ) ;
var builder = new StringBuilder ( ) ;
builder . AppendLine ( "#EXTM3U" ) ;
builder . AppendLine ( "#EXT-X-VERSION:3" ) ;
builder . AppendLine ( "#EXT-X-TARGETDURATION:" + state . SegmentLength . ToString ( UsCulture ) ) ;
builder . AppendLine ( "#EXT-X-MEDIA-SEQUENCE:0" ) ;
var queryStringIndex = Request . RawUrl . IndexOf ( '?' ) ;
var queryString = queryStringIndex = = - 1 ? string . Empty : Request . RawUrl . Substring ( queryStringIndex ) ;
var seconds = TimeSpan . FromTicks ( state . RunTimeTicks ? ? 0 ) . TotalSeconds ;
var index = 0 ;
while ( seconds > 0 )
{
var length = seconds > = state . SegmentLength ? state . SegmentLength : seconds ;
builder . AppendLine ( "#EXTINF:" + length . ToString ( UsCulture ) ) ;
builder . AppendLine ( string . Format ( "hls/{0}/{1}.ts{2}" ,
name ,
index . ToString ( UsCulture ) ,
queryString ) ) ;
seconds - = state . SegmentLength ;
index + + ;
}
builder . AppendLine ( "#EXT-X-ENDLIST" ) ;
var playlistText = builder . ToString ( ) ;
return ResultFactory . GetResult ( playlistText , MimeTypes . GetMimeType ( "playlist.m3u8" ) , new Dictionary < string , string > ( ) ) ;
}
private async Task < object > GetAsync ( GetMasterHlsVideoStream request )
{
var state = await GetState ( request , CancellationToken . None ) . ConfigureAwait ( false ) ;
if ( ! state . VideoRequest . VideoBitRate . HasValue & & ( ! state . VideoRequest . VideoCodec . HasValue | | state . VideoRequest . VideoCodec . Value ! = VideoCodecs . Copy ) )
{
throw new ArgumentException ( "A video bitrate is required" ) ;
}
if ( ! state . Request . AudioBitRate . HasValue & & ( ! state . Request . AudioCodec . HasValue | | state . Request . AudioCodec . Value ! = AudioCodecs . Copy ) )
{
throw new ArgumentException ( "An audio bitrate is required" ) ;
}
int audioBitrate ;
int videoBitrate ;
GetPlaylistBitrates ( state , out audioBitrate , out videoBitrate ) ;
var appendBaselineStream = false ;
var baselineStreamBitrate = 64000 ;
var hlsVideoRequest = state . VideoRequest as GetMasterHlsVideoStream ;
if ( hlsVideoRequest ! = null )
{
appendBaselineStream = hlsVideoRequest . AppendBaselineStream ;
baselineStreamBitrate = hlsVideoRequest . BaselineStreamAudioBitRate ? ? baselineStreamBitrate ;
}
var playlistText = GetMasterPlaylistFileText ( videoBitrate + audioBitrate , appendBaselineStream , baselineStreamBitrate ) ;
return ResultFactory . GetResult ( playlistText , MimeTypes . GetMimeType ( "playlist.m3u8" ) , new Dictionary < string , string > ( ) ) ;
}
private string GetMasterPlaylistFileText ( int bitrate , bool includeBaselineStream , int baselineStreamBitrate )
{
var builder = new StringBuilder ( ) ;
builder . AppendLine ( "#EXTM3U" ) ;
// Pad a little to satisfy the apple hls validator
var paddedBitrate = Convert . ToInt32 ( bitrate * 1.05 ) ;
var queryStringIndex = Request . RawUrl . IndexOf ( '?' ) ;
var queryString = queryStringIndex = = - 1 ? string . Empty : Request . RawUrl . Substring ( queryStringIndex ) ;
// Main stream
builder . AppendLine ( "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate . ToString ( UsCulture ) ) ;
var playlistUrl = "main.m3u8" + queryString ;
builder . AppendLine ( playlistUrl ) ;
// Low bitrate stream
if ( includeBaselineStream )
{
builder . AppendLine ( "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate . ToString ( UsCulture ) ) ;
playlistUrl = "baseline.m3u8" + queryString ;
builder . AppendLine ( playlistUrl ) ;
}
return builder . ToString ( ) ;
}
2013-03-09 06:13:10 +00:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetHlsVideoStream request )
{
return ProcessRequest ( request ) ;
}
2013-04-29 16:01:23 +00:00
2013-02-27 23:33:40 +00:00
/// <summary>
/// Gets the audio arguments.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
protected override string GetAudioArguments ( StreamState state )
{
2013-03-20 14:27:56 +00:00
var codec = GetAudioCodec ( state . Request ) ;
if ( codec . Equals ( "copy" , StringComparison . OrdinalIgnoreCase ) )
2013-02-27 23:33:40 +00:00
{
return "-codec:a:0 copy" ;
}
var args = "-codec:a:0 " + codec ;
if ( state . AudioStream ! = null )
{
var channels = GetNumAudioChannelsParam ( state . Request , state . AudioStream ) ;
if ( channels . HasValue )
{
args + = " -ac " + channels . Value ;
}
2013-08-30 02:13:58 +00:00
var bitrate = GetAudioBitrateParam ( state ) ;
if ( bitrate . HasValue )
2013-02-27 23:33:40 +00:00
{
2013-08-30 02:13:58 +00:00
args + = " -ab " + bitrate . Value . ToString ( UsCulture ) ;
2013-02-27 23:33:40 +00:00
}
2014-01-10 13:52:01 +00:00
args + = " " + GetAudioFilterParam ( state , true ) ;
2013-03-20 14:27:56 +00:00
2013-02-27 23:33:40 +00:00
return args ;
}
return args ;
}
/// <summary>
/// Gets the video arguments.
/// </summary>
/// <param name="state">The state.</param>
2013-04-29 16:01:23 +00:00
/// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
2013-02-27 23:33:40 +00:00
/// <returns>System.String.</returns>
2013-04-29 16:01:23 +00:00
protected override string GetVideoArguments ( StreamState state , bool performSubtitleConversion )
2013-02-27 23:33:40 +00:00
{
2013-03-09 02:34:54 +00:00
var codec = GetVideoCodec ( state . VideoRequest ) ;
2013-02-27 23:33:40 +00:00
// See if we can save come cpu cycles by avoiding encoding
if ( codec . Equals ( "copy" , StringComparison . OrdinalIgnoreCase ) )
{
return IsH264 ( state . VideoStream ) ? "-codec:v:0 copy -bsf h264_mp4toannexb" : "-codec:v:0 copy" ;
}
2013-09-02 20:19:11 +00:00
const string keyFrameArg = " -force_key_frames expr:if(isnan(prev_forced_t),gte(t,.1),gte(t,prev_forced_t+5))" ;
2013-03-28 15:22:05 +00:00
2013-11-20 15:50:54 +00:00
var hasGraphicalSubs = state . SubtitleStream ! = null & & ! state . SubtitleStream . IsExternal & &
( state . SubtitleStream . Codec . IndexOf ( "pgs" , StringComparison . OrdinalIgnoreCase ) ! = - 1 | |
state . SubtitleStream . Codec . IndexOf ( "dvd" , StringComparison . OrdinalIgnoreCase ) ! = - 1 ) ;
2013-12-06 03:39:44 +00:00
2013-12-15 19:39:21 +00:00
var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam ( state , "libx264" ) + keyFrameArg ;
2013-02-27 23:33:40 +00:00
2013-08-30 02:13:58 +00:00
var bitrate = GetVideoBitrateParam ( state ) ;
2013-02-27 23:33:40 +00:00
2013-08-30 02:13:58 +00:00
if ( bitrate . HasValue )
{
2013-12-15 07:25:33 +00:00
args + = string . Format ( " -b:v {0} -maxrate ({0}*.80) -bufsize {0}" , bitrate . Value . ToString ( UsCulture ) ) ;
2013-06-02 14:47:28 +00:00
}
2013-12-06 03:39:44 +00:00
2013-02-27 23:33:40 +00:00
// Add resolution params, if specified
2013-11-20 15:50:54 +00:00
if ( ! hasGraphicalSubs )
2013-02-27 23:33:40 +00:00
{
2013-11-20 15:50:54 +00:00
if ( state . VideoRequest . Width . HasValue | | state . VideoRequest . Height . HasValue | | state . VideoRequest . MaxHeight . HasValue | | state . VideoRequest . MaxWidth . HasValue )
{
args + = GetOutputSizeParam ( state , codec , performSubtitleConversion ) ;
}
2013-02-27 23:33:40 +00:00
}
2013-11-13 16:45:58 +00:00
if ( state . VideoRequest . Framerate . HasValue )
2013-02-27 23:33:40 +00:00
{
2013-11-13 16:45:58 +00:00
args + = string . Format ( " -r {0}" , state . VideoRequest . Framerate . Value ) ;
2013-02-27 23:33:40 +00:00
}
2013-03-20 14:27:56 +00:00
args + = " -vsync vfr" ;
2013-03-24 03:56:01 +00:00
2013-03-28 14:42:03 +00:00
if ( ! string . IsNullOrEmpty ( state . VideoRequest . Profile ) )
{
2013-03-29 12:26:40 +00:00
args + = " -profile:v " + state . VideoRequest . Profile ;
2013-03-28 14:42:03 +00:00
}
if ( ! string . IsNullOrEmpty ( state . VideoRequest . Level ) )
{
2013-03-29 05:45:45 +00:00
args + = " -level " + state . VideoRequest . Level ;
2013-03-28 14:42:03 +00:00
}
2013-11-20 15:50:54 +00:00
// This is for internal graphical subs
if ( hasGraphicalSubs )
2013-03-24 03:56:01 +00:00
{
2013-11-20 15:50:54 +00:00
args + = GetInternalGraphicalSubtitleParam ( state , codec ) ;
2013-03-24 03:56:01 +00:00
}
2013-12-06 03:39:44 +00:00
2013-02-27 23:33:40 +00:00
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 )
{
return ".ts" ;
}
2014-01-13 05:41:00 +00:00
/// <summary>
/// Called when [begin request].
/// </summary>
/// <param name="playlistId">The playlist id.</param>
protected void OnBeginRequest ( string playlistId )
{
var normalizedPlaylistId = playlistId . Replace ( "-low" , string . Empty ) ;
foreach ( var playlist in Directory . EnumerateFiles ( ServerConfigurationManager . ApplicationPaths . TranscodingTempPath , "*.m3u8" )
. Where ( i = > i . IndexOf ( normalizedPlaylistId , StringComparison . OrdinalIgnoreCase ) ! = - 1 )
. ToList ( ) )
{
ExtendPlaylistTimer ( playlist ) ;
}
}
private async void ExtendPlaylistTimer ( string playlist )
{
ApiEntryPoint . Instance . OnTranscodeBeginRequest ( playlist , TranscodingJobType . Hls ) ;
await Task . Delay ( 20000 ) . ConfigureAwait ( false ) ;
ApiEntryPoint . Instance . OnTranscodeEndRequest ( playlist , TranscodingJobType . Hls ) ;
}
2013-02-27 23:33:40 +00:00
}
}