jellyfin-server/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs

337 lines
13 KiB
C#
Raw Normal View History

2013-06-18 10:36:25 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
2013-02-21 01:33:05 +00:00
using MediaBrowser.Common.Net;
2014-05-18 19:58:42 +00:00
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
2014-03-25 05:25:03 +00:00
using MediaBrowser.Controller.Dlna;
2013-09-04 17:02:19 +00:00
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Library;
2013-12-21 18:37:34 +00:00
using MediaBrowser.Controller.LiveTv;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
2013-12-06 03:39:44 +00:00
using MediaBrowser.Controller.Persistence;
using MediaBrowser.Model.Configuration;
2013-08-28 22:05:00 +00:00
using MediaBrowser.Model.IO;
2013-02-21 01:33:05 +00:00
using System;
using System.Collections.Generic;
2013-02-21 01:33:05 +00:00
using System.IO;
2013-08-28 22:05:00 +00:00
using System.Text;
2013-12-21 18:37:34 +00:00
using System.Threading;
2013-02-21 01:33:05 +00:00
using System.Threading.Tasks;
namespace MediaBrowser.Api.Playback.Hls
2013-02-21 01:33:05 +00:00
{
2013-04-29 16:01:23 +00:00
/// <summary>
/// Class BaseHlsService
/// </summary>
public abstract class BaseHlsService : BaseStreamingService
2013-02-21 01:33:05 +00:00
{
2014-06-02 19:32:41 +00:00
protected BaseHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IDtoService dtoService, IFileSystem fileSystem, IItemRepository itemRepository, ILiveTvManager liveTvManager, IEncodingManager encodingManager, IDlnaManager dlnaManager, IChannelManager channelManager, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, dtoService, fileSystem, itemRepository, liveTvManager, encodingManager, dlnaManager, channelManager, httpClient)
2013-12-06 03:39:44 +00:00
{
}
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the audio arguments.
/// </summary>
2013-04-29 16:01:23 +00:00
/// <param name="state">The state.</param>
2013-02-21 01:33:05 +00:00
/// <returns>System.String.</returns>
protected abstract string GetAudioArguments(StreamState state);
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the video arguments.
/// </summary>
2013-04-29 16:01:23 +00:00
/// <param name="state">The state.</param>
/// <param name="performSubtitleConversion">if set to <c>true</c> [perform subtitle conversion].</param>
2013-02-21 01:33:05 +00:00
/// <returns>System.String.</returns>
2013-04-29 16:01:23 +00:00
protected abstract string GetVideoArguments(StreamState state, bool performSubtitleConversion);
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the segment file extension.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
protected abstract string GetSegmentFileExtension(StreamState state);
2013-04-29 16:01:23 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the type of the transcoding job.
/// </summary>
/// <value>The type of the transcoding job.</value>
protected override TranscodingJobType TranscodingJobType
{
get { return TranscodingJobType.Hls; }
}
/// <summary>
/// Processes the request.
2013-02-21 01:33:05 +00:00
/// </summary>
2013-04-29 16:01:23 +00:00
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
protected object ProcessRequest(StreamRequest request)
2013-02-21 01:33:05 +00:00
{
2014-01-12 21:32:13 +00:00
return ProcessRequestAsync(request).Result;
2013-02-21 01:33:05 +00:00
}
2014-04-15 03:54:52 +00:00
private static readonly SemaphoreSlim FfmpegStartLock = new SemaphoreSlim(1, 1);
2013-02-21 01:33:05 +00:00
/// <summary>
/// Processes the request async.
2013-02-21 01:33:05 +00:00
/// </summary>
2014-01-12 21:32:13 +00:00
/// <param name="request">The request.</param>
/// <returns>Task{System.Object}.</returns>
2014-01-12 21:32:13 +00:00
/// <exception cref="ArgumentException">
/// A video bitrate is required
/// or
/// An audio bitrate is required
/// </exception>
private async Task<object> ProcessRequestAsync(StreamRequest request)
2013-02-21 01:33:05 +00:00
{
2014-06-02 19:32:41 +00:00
var cancellationTokenSource = new CancellationTokenSource();
var state = GetState(request, cancellationTokenSource.Token).Result;
2014-01-12 21:32:13 +00:00
var playlist = state.OutputFilePath;
2013-02-21 01:33:05 +00:00
2014-04-15 03:54:52 +00:00
if (File.Exists(playlist))
2013-02-21 01:33:05 +00:00
{
2014-04-15 03:54:52 +00:00
ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
}
else
{
2014-06-02 19:32:41 +00:00
await FfmpegStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
2014-04-05 15:02:50 +00:00
try
{
2014-04-15 03:54:52 +00:00
if (File.Exists(playlist))
{
ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlist, TranscodingJobType.Hls);
}
else
{
// If the playlist doesn't already exist, startup ffmpeg
try
{
2014-06-02 19:32:41 +00:00
await StartFfMpeg(state, playlist, cancellationTokenSource).ConfigureAwait(false);
2014-04-15 03:54:52 +00:00
}
catch
{
state.Dispose();
throw;
}
2014-06-02 19:32:41 +00:00
await WaitForMinimumSegmentCount(playlist, GetSegmentWait(), cancellationTokenSource.Token).ConfigureAwait(false);
}
2014-04-05 15:02:50 +00:00
}
2014-04-15 03:54:52 +00:00
finally
2014-04-05 15:02:50 +00:00
{
2014-04-15 03:54:52 +00:00
FfmpegStartLock.Release();
2014-04-05 15:02:50 +00:00
}
2013-02-21 01:33:05 +00:00
}
2013-08-28 22:05:00 +00:00
2013-10-07 18:22:21 +00:00
int audioBitrate;
int videoBitrate;
GetPlaylistBitrates(state, out audioBitrate, out videoBitrate);
2013-08-30 02:13:58 +00:00
2013-09-06 17:27:06 +00:00
var appendBaselineStream = false;
var baselineStreamBitrate = 64000;
var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
if (hlsVideoRequest != null)
{
appendBaselineStream = hlsVideoRequest.AppendBaselineStream;
baselineStreamBitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? baselineStreamBitrate;
}
var playlistText = GetMasterPlaylistFileText(playlist, videoBitrate + audioBitrate, appendBaselineStream, baselineStreamBitrate);
2013-02-21 01:33:05 +00:00
try
{
return ResultFactory.GetResult(playlistText, MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
2013-02-21 01:33:05 +00:00
}
finally
{
2013-03-08 19:14:09 +00:00
ApiEntryPoint.Instance.OnTranscodeEndRequest(playlist, TranscodingJobType.Hls);
2013-02-21 01:33:05 +00:00
}
}
2013-10-07 18:22:21 +00:00
2014-01-23 18:05:41 +00:00
/// <summary>
/// Gets the segment wait.
/// </summary>
/// <returns>System.Int32.</returns>
protected int GetSegmentWait()
{
var minimumSegmentCount = 3;
var quality = GetQualitySetting();
if (quality == EncodingQuality.HighSpeed || quality == EncodingQuality.HighQuality)
{
minimumSegmentCount = 2;
}
return minimumSegmentCount;
}
2013-10-07 18:22:21 +00:00
/// <summary>
/// Gets the playlist bitrates.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="audioBitrate">The audio bitrate.</param>
/// <param name="videoBitrate">The video bitrate.</param>
2014-01-12 21:32:13 +00:00
protected void GetPlaylistBitrates(StreamState state, out int audioBitrate, out int videoBitrate)
2013-10-07 18:22:21 +00:00
{
var audioBitrateParam = state.OutputAudioBitrate;
var videoBitrateParam = state.OutputVideoBitrate;
2013-10-07 18:22:21 +00:00
if (!audioBitrateParam.HasValue)
{
if (state.AudioStream != null)
{
audioBitrateParam = state.AudioStream.BitRate;
}
}
if (!videoBitrateParam.HasValue)
{
if (state.VideoStream != null)
{
videoBitrateParam = state.VideoStream.BitRate;
}
}
audioBitrate = audioBitrateParam ?? 0;
videoBitrate = videoBitrateParam ?? 0;
}
2013-02-21 01:33:05 +00:00
2013-09-06 17:27:06 +00:00
private string GetMasterPlaylistFileText(string firstPlaylist, int bitrate, bool includeBaselineStream, int baselineStreamBitrate)
2013-02-21 01:33:05 +00:00
{
2013-08-28 22:05:00 +00:00
var builder = new StringBuilder();
builder.AppendLine("#EXTM3U");
2013-09-03 14:37:15 +00:00
// Pad a little to satisfy the apple hls validator
2014-03-27 19:30:21 +00:00
var paddedBitrate = Convert.ToInt32(bitrate * 1.15);
2013-09-03 14:37:15 +00:00
2013-08-28 22:05:00 +00:00
// Main stream
2013-09-03 14:37:15 +00:00
builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture));
2013-08-28 22:05:00 +00:00
var playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "/stream.m3u8");
builder.AppendLine(playlistUrl);
2013-02-21 01:33:05 +00:00
2013-08-28 22:05:00 +00:00
// Low bitrate stream
2013-09-06 17:27:06 +00:00
if (includeBaselineStream)
{
builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + baselineStreamBitrate.ToString(UsCulture));
playlistUrl = "hls/" + Path.GetFileName(firstPlaylist).Replace(".m3u8", "-low/stream.m3u8");
builder.AppendLine(playlistUrl);
}
2013-08-28 22:05:00 +00:00
return builder.ToString();
}
2014-06-02 19:32:41 +00:00
protected async Task WaitForMinimumSegmentCount(string playlist, int segmentCount, CancellationToken cancellationToken)
2013-08-28 22:05:00 +00:00
{
2013-02-21 01:33:05 +00:00
while (true)
{
2014-06-02 19:32:41 +00:00
cancellationToken.ThrowIfCancellationRequested();
2013-08-28 22:05:00 +00:00
string fileText;
2013-02-21 01:33:05 +00:00
// Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
using (var fileStream = FileSystem.GetFileStream(playlist, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
2013-02-21 01:33:05 +00:00
{
using (var reader = new StreamReader(fileStream))
{
fileText = await reader.ReadToEndAsync().ConfigureAwait(false);
}
}
2013-08-28 22:05:00 +00:00
if (CountStringOccurrences(fileText, "#EXTINF:") >= segmentCount)
2013-02-21 01:33:05 +00:00
{
break;
}
2014-06-02 19:32:41 +00:00
await Task.Delay(25, cancellationToken).ConfigureAwait(false);
2013-02-21 01:33:05 +00:00
}
}
/// <summary>
/// Count occurrences of strings.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="pattern">The pattern.</param>
/// <returns>System.Int32.</returns>
private static int CountStringOccurrences(string text, string pattern)
{
// Loop through all instances of the string 'text'.
var count = 0;
var i = 0;
while ((i = text.IndexOf(pattern, i, StringComparison.OrdinalIgnoreCase)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
2013-04-29 16:01:23 +00:00
2013-02-21 01:33:05 +00:00
/// <summary>
/// Gets the command line arguments.
2013-02-21 01:33:05 +00:00
/// </summary>
/// <param name="outputPath">The output path.</param>
/// <param name="state">The state.</param>
2013-04-29 16:01:23 +00:00
/// <param name="performSubtitleConversions">if set to <c>true</c> [perform subtitle conversions].</param>
2013-02-21 01:33:05 +00:00
/// <returns>System.String.</returns>
2013-04-29 16:01:23 +00:00
protected override string GetCommandLineArguments(string outputPath, StreamState state, bool performSubtitleConversions)
2013-02-21 01:33:05 +00:00
{
var hlsVideoRequest = state.VideoRequest as GetHlsVideoStream;
var itsOffsetMs = hlsVideoRequest == null
? 0
2013-12-06 03:39:44 +00:00
: ((GetHlsVideoStream)state.VideoRequest).TimeStampOffsetMs;
2014-03-31 01:00:47 +00:00
var itsOffset = itsOffsetMs == 0 ? string.Empty : string.Format("-itsoffset {0} ", TimeSpan.FromMilliseconds(itsOffsetMs).TotalSeconds.ToString(UsCulture));
var threads = GetNumberOfThreads(state, false);
2014-01-22 01:37:01 +00:00
var inputModifier = GetInputModifier(state);
2014-01-23 18:05:41 +00:00
// If performSubtitleConversions is true we're actually starting ffmpeg
var startNumberParam = performSubtitleConversions ? GetStartNumber(state).ToString(UsCulture) : "0";
2014-04-15 03:54:52 +00:00
2014-06-02 19:32:41 +00:00
var args = string.Format("{0} {1} -i {2} -map_metadata -1 -threads {3} {4} {5} -sc_threshold 0 {6} -hls_time {7} -start_number {8} -hls_list_size {9} -y \"{10}\"",
itsOffset,
2014-01-22 01:37:01 +00:00
inputModifier,
2013-12-19 21:51:32 +00:00
GetInputArgument(state),
threads,
GetMapArgs(state),
2013-04-29 16:01:23 +00:00
GetVideoArguments(state, performSubtitleConversions),
GetAudioArguments(state),
2014-01-12 21:32:13 +00:00
state.SegmentLength.ToString(UsCulture),
2014-01-23 18:05:41 +00:00
startNumberParam,
2014-03-04 04:58:19 +00:00
state.HlsListSize.ToString(UsCulture),
2013-08-28 22:05:00 +00:00
outputPath
2013-02-21 01:33:05 +00:00
).Trim();
2013-08-28 22:05:00 +00:00
2013-09-06 17:27:06 +00:00
if (hlsVideoRequest != null)
2013-08-28 22:05:00 +00:00
{
if (hlsVideoRequest.AppendBaselineStream)
2013-09-06 17:27:06 +00:00
{
var lowBitratePath = Path.Combine(Path.GetDirectoryName(outputPath), Path.GetFileNameWithoutExtension(outputPath) + "-low.m3u8");
2013-08-28 22:05:00 +00:00
2013-09-06 17:27:06 +00:00
var bitrate = hlsVideoRequest.BaselineStreamAudioBitRate ?? 64000;
2013-08-28 22:05:00 +00:00
2014-06-02 19:32:41 +00:00
var lowBitrateParams = string.Format(" -threads {0} -vn -codec:a:0 libmp3lame -ac 2 -ab {1} -hls_time {2} -start_number {3} -hls_list_size {4} -y \"{5}\"",
threads,
2014-01-12 21:32:13 +00:00
bitrate / 2,
state.SegmentLength.ToString(UsCulture),
2014-01-23 18:05:41 +00:00
startNumberParam,
2014-03-04 04:58:19 +00:00
state.HlsListSize.ToString(UsCulture),
2014-01-12 21:32:13 +00:00
lowBitratePath);
2013-09-06 17:27:06 +00:00
args += " " + lowBitrateParams;
}
2013-08-28 22:05:00 +00:00
}
return args;
2013-02-21 01:33:05 +00:00
}
2014-01-23 18:05:41 +00:00
protected virtual int GetStartNumber(StreamState state)
{
return 0;
}
2013-02-21 01:33:05 +00:00
}
}