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

707 lines
25 KiB
C#
Raw Normal View History

2014-08-21 15:55:35 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
2014-09-10 00:28:59 +00:00
using MediaBrowser.Common.Net;
2014-05-18 19:58:42 +00:00
using MediaBrowser.Controller.Channels;
2014-01-23 18:05:41 +00:00
using MediaBrowser.Controller.Configuration;
2014-03-25 05:25:03 +00:00
using MediaBrowser.Controller.Dlna;
2014-01-23 18:05:41 +00:00
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.LiveTv;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
2014-09-03 02:30:24 +00:00
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Dlna;
using MediaBrowser.Model.Entities;
2014-01-23 18:05:41 +00:00
using MediaBrowser.Model.IO;
using ServiceStack;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
2014-06-26 17:04:11 +00:00
using System.Linq;
2014-01-23 18:05:41 +00:00
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Api.Playback.Hls
{
2014-08-17 05:38:13 +00:00
/// <summary>
/// Options is needed for chromecast. Threw Head in there since it's related
/// </summary>
[Route("/Videos/{Id}/master.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
2014-08-17 05:38:13 +00:00
[Route("/Videos/{Id}/master.m3u8", "HEAD", Summary = "Gets a video stream using HTTP live streaming.")]
2014-01-23 18:05:41 +00:00
public class GetMasterHlsVideoStream : VideoStreamRequest
{
2014-08-01 02:58:37 +00:00
public bool EnableAdaptiveBitrateStreaming { get; set; }
public GetMasterHlsVideoStream()
{
EnableAdaptiveBitrateStreaming = true;
}
2014-01-23 18:05:41 +00:00
}
[Route("/Videos/{Id}/main.m3u8", "GET", Summary = "Gets a video stream using HTTP live streaming.")]
2014-01-23 18:05:41 +00:00
public class GetMainHlsVideoStream : VideoStreamRequest
{
}
/// <summary>
/// Class GetHlsVideoSegment
/// </summary>
[Route("/Videos/{Id}/hlsdynamic/{PlaylistId}/{SegmentId}.ts", "GET")]
[Api(Description = "Gets an Http live streaming segment file. Internal use only.")]
public class GetDynamicHlsVideoSegment : VideoStreamRequest
{
public string PlaylistId { get; set; }
/// <summary>
/// Gets or sets the segment id.
/// </summary>
/// <value>The segment id.</value>
public string SegmentId { get; set; }
}
public class DynamicHlsService : BaseHlsService
{
2014-09-10 00:28:59 +00:00
protected INetworkManager NetworkManager { get; private set; }
public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder, INetworkManager networkManager)
2014-06-26 17:04:11 +00:00
: base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
2014-01-23 18:05:41 +00:00
{
2014-09-10 00:28:59 +00:00
NetworkManager = networkManager;
2014-01-23 18:05:41 +00:00
}
public object Get(GetMasterHlsVideoStream request)
{
2014-08-17 05:38:13 +00:00
var result = GetAsync(request, "GET").Result;
return result;
}
public object Head(GetMasterHlsVideoStream request)
{
var result = GetAsync(request, "HEAD").Result;
2014-01-23 18:05:41 +00:00
return result;
}
2014-07-04 05:59:30 +00:00
public object Get(GetMainHlsVideoStream request)
{
var result = GetPlaylistAsync(request, "main").Result;
return result;
}
2014-01-23 18:05:41 +00:00
public object Get(GetDynamicHlsVideoSegment request)
{
2014-07-04 05:59:30 +00:00
return GetDynamicSegment(request, request.SegmentId).Result;
2014-01-23 18:05:41 +00:00
}
2014-07-04 05:59:30 +00:00
private async Task<object> GetDynamicSegment(VideoStreamRequest request, string segmentId)
2014-01-23 18:05:41 +00:00
{
2014-06-26 17:04:11 +00:00
if ((request.StartTimeTicks ?? 0) > 0)
{
throw new ArgumentException("StartTimeTicks is not allowed.");
}
2014-06-20 04:50:30 +00:00
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
2014-07-04 05:59:30 +00:00
var index = int.Parse(segmentId, NumberStyles.Integer, UsCulture);
2014-01-23 18:05:41 +00:00
2014-06-20 04:50:30 +00:00
var state = await GetState(request, cancellationToken).ConfigureAwait(false);
2014-01-23 18:05:41 +00:00
var playlistPath = Path.ChangeExtension(state.OutputFilePath, ".m3u8");
2014-01-23 18:05:41 +00:00
2014-06-20 04:50:30 +00:00
var segmentPath = GetSegmentPath(playlistPath, index);
2014-09-03 02:30:24 +00:00
var segmentLength = state.SegmentLength;
TranscodingJob job = null;
2014-01-23 18:05:41 +00:00
2014-06-20 04:50:30 +00:00
if (File.Exists(segmentPath))
2014-01-23 18:05:41 +00:00
{
2014-09-03 02:30:24 +00:00
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
2014-01-23 18:05:41 +00:00
}
2014-07-02 18:34:08 +00:00
await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
2014-06-20 04:50:30 +00:00
try
{
if (File.Exists(segmentPath))
{
2014-09-03 02:30:24 +00:00
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
2014-06-20 04:50:30 +00:00
}
else
{
2014-06-26 17:04:11 +00:00
var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
2014-06-28 02:43:10 +00:00
if (currentTranscodingIndex == null || index < currentTranscodingIndex.Value || (index - currentTranscodingIndex.Value) > 4)
2014-06-20 04:50:30 +00:00
{
// If the playlist doesn't already exist, startup ffmpeg
try
{
2014-09-22 21:56:54 +00:00
await ApiEntryPoint.Instance.KillTranscodingJobs(j => j.Type == TranscodingJobType.Hls && string.Equals(j.DeviceId, request.DeviceId, StringComparison.OrdinalIgnoreCase), p => !string.Equals(p, playlistPath, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false);
2014-07-02 18:34:08 +00:00
2014-06-26 17:04:11 +00:00
if (currentTranscodingIndex.HasValue)
{
DeleteLastFile(playlistPath, 0);
}
var startSeconds = index * state.SegmentLength;
request.StartTimeTicks = TimeSpan.FromSeconds(startSeconds).Ticks;
2014-06-20 04:50:30 +00:00
2014-09-03 02:30:24 +00:00
job = await StartFfMpeg(state, playlistPath, cancellationTokenSource).ConfigureAwait(false);
2014-06-20 04:50:30 +00:00
}
catch
{
state.Dispose();
throw;
}
2014-06-26 17:04:11 +00:00
await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
2014-06-20 04:50:30 +00:00
}
}
}
finally
2014-01-23 18:05:41 +00:00
{
2014-07-02 18:34:08 +00:00
ApiEntryPoint.Instance.TranscodingStartLock.Release();
2014-06-20 04:50:30 +00:00
}
2014-01-23 18:05:41 +00:00
2014-06-20 04:50:30 +00:00
Logger.Info("waiting for {0}", segmentPath);
while (!File.Exists(segmentPath))
{
await Task.Delay(50, cancellationToken).ConfigureAwait(false);
2014-01-23 18:05:41 +00:00
}
2014-06-20 04:50:30 +00:00
Logger.Info("returning {0}", segmentPath);
2014-09-03 02:30:24 +00:00
job = job ?? ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType.Hls);
return await GetSegmentResult(playlistPath, segmentPath, index, segmentLength, job, cancellationToken).ConfigureAwait(false);
2014-06-26 17:04:11 +00:00
}
public int? GetCurrentTranscodingIndex(string playlist)
{
var file = GetLastTranscodingFile(playlist, 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, int retryCount)
{
if (retryCount >= 5)
{
return;
}
var file = GetLastTranscodingFile(path, FileSystem);
if (file != null)
{
try
{
File.Delete(file.FullName);
}
catch (IOException ex)
{
Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
Thread.Sleep(100);
DeleteLastFile(path, retryCount + 1);
}
catch (Exception ex)
{
Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, file.FullName);
}
}
}
private static FileInfo GetLastTranscodingFile(string playlist, IFileSystem fileSystem)
{
var folder = Path.GetDirectoryName(playlist);
try
{
return new DirectoryInfo(folder)
.EnumerateFiles("*", SearchOption.TopDirectoryOnly)
.Where(i => string.Equals(i.Extension, ".ts", StringComparison.OrdinalIgnoreCase))
.OrderByDescending(fileSystem.GetLastWriteTimeUtc)
.FirstOrDefault();
}
catch (DirectoryNotFoundException)
{
return null;
}
2014-06-20 04:50:30 +00:00
}
protected override int GetStartNumber(StreamState state)
{
2014-07-04 05:59:30 +00:00
return GetStartNumber(state.VideoRequest);
}
private int GetStartNumber(VideoStreamRequest request)
{
var segmentId = "0";
2014-06-20 04:50:30 +00:00
2014-07-04 05:59:30 +00:00
var segmentRequest = request as GetDynamicHlsVideoSegment;
if (segmentRequest != null)
{
segmentId = segmentRequest.SegmentId;
}
return int.Parse(segmentId, NumberStyles.Integer, UsCulture);
2014-01-23 18:05:41 +00:00
}
private string GetSegmentPath(string playlist, int index)
{
var folder = Path.GetDirectoryName(playlist);
var filename = Path.GetFileNameWithoutExtension(playlist);
return Path.Combine(folder, filename + index.ToString(UsCulture) + ".ts");
}
2014-09-03 02:30:24 +00:00
private async Task<object> GetSegmentResult(string playlistPath,
string segmentPath,
int segmentIndex,
int segmentLength,
TranscodingJob transcodingJob,
CancellationToken cancellationToken)
2014-06-26 17:04:11 +00:00
{
// If all transcoding has completed, just return immediately
if (!IsTranscoding(playlistPath))
{
2014-09-03 02:30:24 +00:00
return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
2014-06-26 17:04:11 +00:00
}
var segmentFilename = Path.GetFileName(segmentPath);
2014-07-27 22:01:29 +00:00
using (var fileStream = FileSystem.GetFileStream(playlistPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
2014-06-26 17:04:11 +00:00
{
2014-07-27 22:01:29 +00:00
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)
{
2014-09-03 02:30:24 +00:00
return GetSegmentResult(segmentPath, segmentIndex, segmentLength, transcodingJob);
2014-07-27 22:01:29 +00:00
}
}
2014-06-26 17:04:11 +00:00
}
// if a different file is encoding, it's done
//var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath);
//if (currentTranscodingIndex > segmentIndex)
//{
2014-09-03 02:30:24 +00:00
//return GetSegmentResult(segmentPath, segmentIndex);
2014-06-26 17:04:11 +00:00
//}
// 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);
}
2014-09-03 02:30:24 +00:00
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);
}
}
});
2014-06-26 17:04:11 +00:00
}
private bool IsTranscoding(string playlistPath)
2014-01-23 18:05:41 +00:00
{
2014-06-26 17:04:11 +00:00
var job = ApiEntryPoint.Instance.GetTranscodingJob(playlistPath, TranscodingJobType);
return job != null && !job.HasExited;
2014-01-23 18:05:41 +00:00
}
2014-08-17 05:38:13 +00:00
private async Task<object> GetAsync(GetMasterHlsVideoStream request, string method)
2014-01-23 18:05:41 +00:00
{
var state = await GetState(request, CancellationToken.None).ConfigureAwait(false);
2014-07-31 02:09:23 +00:00
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");
}
2014-08-17 05:38:13 +00:00
var playlistText = string.Empty;
if (string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
{
var audioBitrate = state.OutputAudioBitrate ?? 0;
var videoBitrate = state.OutputVideoBitrate ?? 0;
2014-01-23 18:05:41 +00:00
2014-08-17 05:38:13 +00:00
playlistText = GetMasterPlaylistFileText(state, videoBitrate + audioBitrate);
}
2014-01-23 18:05:41 +00:00
2014-06-20 04:50:30 +00:00
return ResultFactory.GetResult(playlistText, Common.Net.MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
2014-01-23 18:05:41 +00:00
}
private string GetMasterPlaylistFileText(StreamState state, int totalBitrate)
2014-01-23 18:05:41 +00:00
{
var builder = new StringBuilder();
builder.AppendLine("#EXTM3U");
var queryStringIndex = Request.RawUrl.IndexOf('?');
var queryString = queryStringIndex == -1 ? string.Empty : Request.RawUrl.Substring(queryStringIndex);
// Main stream
2014-07-01 21:13:32 +00:00
var playlistUrl = (state.RunTimeTicks ?? 0) > 0 ? "main.m3u8" : "live.m3u8";
playlistUrl += queryString;
2014-08-17 05:38:13 +00:00
var request = (GetMasterHlsVideoStream)state.Request;
var subtitleStreams = state.AllMediaStreams
.Where(i => i.IsTextSubtitleStream)
.ToList();
2014-08-17 05:38:13 +00:00
var subtitleGroup = subtitleStreams.Count > 0 && request.SubtitleMethod == SubtitleDeliveryMethod.Hls ?
"subs" :
null;
AppendPlaylist(builder, playlistUrl, totalBitrate, subtitleGroup);
2014-07-15 19:16:16 +00:00
if (EnableAdaptiveBitrateStreaming(state))
{
2014-08-21 15:55:35 +00:00
var requestedVideoBitrate = state.VideoRequest.VideoBitRate.Value;
2014-08-21 15:55:35 +00:00
// By default, vary by just 200k
var variation = GetBitrateVariation(totalBitrate);
2014-08-21 15:55:35 +00:00
var newBitrate = totalBitrate - variation;
var variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
2014-08-21 15:55:35 +00:00
variation *= 2;
newBitrate = totalBitrate - variation;
variantUrl = ReplaceBitrate(playlistUrl, requestedVideoBitrate, (requestedVideoBitrate - variation));
AppendPlaylist(builder, variantUrl, newBitrate, subtitleGroup);
}
if (!string.IsNullOrWhiteSpace(subtitleGroup))
{
AddSubtitles(state, subtitleStreams, builder);
}
2014-01-23 18:05:41 +00:00
return builder.ToString();
}
2014-08-21 15:55:35 +00:00
private string ReplaceBitrate(string url, int oldValue, int newValue)
{
return url.Replace(
"videobitrate=" + oldValue.ToString(UsCulture),
"videobitrate=" + newValue.ToString(UsCulture),
StringComparison.OrdinalIgnoreCase);
}
private void AddSubtitles(StreamState state, IEnumerable<MediaStream> subtitles, StringBuilder builder)
{
var selectedIndex = state.SubtitleStream == null ? (int?)null : state.SubtitleStream.Index;
foreach (var stream in subtitles)
{
const string format = "#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID=\"subs\",NAME=\"{0}\",DEFAULT={1},FORCED={2},URI=\"{3}\",LANGUAGE=\"{4}\"";
var name = stream.Language;
var isDefault = selectedIndex.HasValue && selectedIndex.Value == stream.Index;
var isForced = stream.IsForced;
if (string.IsNullOrWhiteSpace(name)) name = stream.Codec ?? "Unknown";
var url = string.Format("{0}/Subtitles/{1}/subtitles.m3u8?SegmentLength={2}",
state.Request.MediaSourceId,
stream.Index.ToString(UsCulture),
30.ToString(UsCulture));
var line = string.Format(format,
name,
isDefault ? "YES" : "NO",
isForced ? "YES" : "NO",
url,
stream.Language ?? "Unknown");
builder.AppendLine(line);
}
}
2014-07-15 19:16:16 +00:00
private bool EnableAdaptiveBitrateStreaming(StreamState state)
{
2014-09-10 00:28:59 +00:00
// Within the local network this will likely do more harm than good.
if (Request.IsLocal || NetworkManager.IsInLocalNetwork(Request.RemoteIp))
{
return false;
}
2014-08-01 02:58:37 +00:00
var request = state.Request as GetMasterHlsVideoStream;
if (request != null && !request.EnableAdaptiveBitrateStreaming)
{
return false;
}
2014-07-15 19:16:16 +00:00
if (string.IsNullOrWhiteSpace(state.MediaPath))
{
// Opening live streams is so slow it's not even worth it
return false;
}
return state.VideoRequest.VideoBitRate.HasValue;
}
private void AppendPlaylist(StringBuilder builder, string url, int bitrate, string subtitleGroup)
{
var header = "#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + bitrate.ToString(UsCulture);
if (!string.IsNullOrWhiteSpace(subtitleGroup))
{
header += string.Format(",SUBTITLES=\"{0}\"", subtitleGroup);
}
builder.AppendLine(header);
builder.AppendLine(url);
}
private int GetBitrateVariation(int bitrate)
{
2014-08-21 15:55:35 +00:00
// By default, vary by just 50k
var variation = 50000;
if (bitrate >= 10000000)
{
variation = 2000000;
}
else if (bitrate >= 5000000)
{
variation = 1500000;
}
else if (bitrate >= 3000000)
{
variation = 1000000;
}
else if (bitrate >= 2000000)
{
variation = 500000;
}
else if (bitrate >= 1000000)
{
variation = 300000;
}
2014-07-15 19:16:16 +00:00
else if (bitrate >= 600000)
{
variation = 200000;
}
2014-08-21 15:55:35 +00:00
else if (bitrate >= 400000)
{
variation = 100000;
}
return variation;
}
2014-01-23 18:05:41 +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");
2014-06-28 02:43:10 +00:00
builder.AppendLine("#EXT-X-ALLOW-CACHE:NO");
2014-01-23 18:05:41 +00:00
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;
2014-07-04 05:59:30 +00:00
builder.AppendLine("#EXTINF:" + length.ToString(UsCulture) + ",");
2014-01-23 18:05:41 +00:00
builder.AppendLine(string.Format("hlsdynamic/{0}/{1}.ts{2}",
name,
index.ToString(UsCulture),
queryString));
seconds -= state.SegmentLength;
index++;
}
builder.AppendLine("#EXT-X-ENDLIST");
var playlistText = builder.ToString();
2014-06-20 04:50:30 +00:00
return ResultFactory.GetResult(playlistText, Common.Net.MimeTypes.GetMimeType("playlist.m3u8"), new Dictionary<string, string>());
2014-01-23 18:05:41 +00:00
}
protected override string GetAudioArguments(StreamState state)
{
var codec = state.OutputAudioCodec;
2014-01-23 18:05:41 +00:00
if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
{
return "-codec:a:0 copy";
}
var args = "-codec:a:0 " + codec;
2014-06-23 16:05:19 +00:00
var channels = state.OutputAudioChannels;
2014-01-23 18:05:41 +00:00
2014-06-23 16:05:19 +00:00
if (channels.HasValue)
{
args += " -ac " + channels.Value;
}
2014-01-23 18:05:41 +00:00
2014-06-23 16:05:19 +00:00
var bitrate = state.OutputAudioBitrate;
2014-01-23 18:05:41 +00:00
2014-06-23 16:05:19 +00:00
if (bitrate.HasValue)
{
args += " -ab " + bitrate.Value.ToString(UsCulture);
2014-01-23 18:05:41 +00:00
}
2014-06-23 16:05:19 +00:00
args += " " + GetAudioFilterParam(state, true);
2014-01-23 18:05:41 +00:00
return args;
}
2014-06-10 17:36:06 +00:00
protected override string GetVideoArguments(StreamState state)
2014-01-23 18:05:41 +00:00
{
var codec = state.OutputVideoCodec;
2014-01-23 18:05:41 +00:00
// See if we can save come cpu cycles by avoiding encoding
if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
{
2014-10-04 18:05:24 +00:00
return IsH264(state.VideoStream) ? "-codec:v:0 copy -bsf:v h264_mp4toannexb" : "-codec:v:0 copy";
2014-01-23 18:05:41 +00:00
}
2014-06-26 17:04:11 +00:00
var keyFrameArg = string.Format(" -force_key_frames expr:gte(t,n_forced*{0})",
state.SegmentLength.ToString(UsCulture));
2014-01-23 18:05:41 +00:00
2014-06-11 20:57:18 +00:00
var hasGraphicalSubs = state.SubtitleStream != null && !state.SubtitleStream.IsTextSubtitleStream;
2014-01-23 18:05:41 +00:00
2014-02-02 14:47:00 +00:00
var args = "-codec:v:0 " + codec + " " + GetVideoQualityParam(state, "libx264", true) + keyFrameArg;
2014-01-23 18:05:41 +00:00
// Add resolution params, if specified
if (!hasGraphicalSubs)
{
2014-08-17 05:38:13 +00:00
args += GetOutputSizeParam(state, codec, false);
2014-01-23 18:05:41 +00:00
}
// This is for internal graphical subs
if (hasGraphicalSubs)
{
2014-07-30 03:31:35 +00:00
args += GetGraphicalSubtitleParam(state, codec);
2014-01-23 18:05:41 +00:00
}
return args;
}
2014-09-03 02:30:24 +00:00
protected override string GetCommandLineArguments(string outputPath, string transcodingJobId, StreamState state, bool isEncoding)
2014-06-28 02:43:10 +00:00
{
var threads = GetNumberOfThreads(state, false);
var inputModifier = GetInputModifier(state);
// If isEncoding is true we're actually starting ffmpeg
var startNumberParam = isEncoding ? GetStartNumber(state).ToString(UsCulture) : "0";
var args = string.Format("{0} -i {1} -map_metadata -1 -threads {2} {3} {4} -copyts -flags -global_header {5} -hls_time {6} -start_number {7} -hls_list_size {8} -y \"{9}\"",
2014-06-28 02:43:10 +00:00
inputModifier,
2014-09-03 02:30:24 +00:00
GetInputArgument(transcodingJobId, state),
2014-06-28 02:43:10 +00:00
threads,
GetMapArgs(state),
GetVideoArguments(state),
GetAudioArguments(state),
state.SegmentLength.ToString(UsCulture),
startNumberParam,
state.HlsListSize.ToString(UsCulture),
outputPath
).Trim();
return args;
}
2014-01-23 18:05:41 +00:00
/// <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-06-26 17:04:11 +00:00
protected override TranscodingJobType TranscodingJobType
{
get
{
return TranscodingJobType.Hls;
}
}
2014-01-23 18:05:41 +00:00
}
}