mirror of
https://github.com/jellyfin/jellyfin.git
synced 2026-03-06 10:16:18 +00:00
Port MediaEncoding and Api.Playback from 10e57ce8d21b4516733894075001819f3cd6db6b
This commit is contained in:
201
MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs
Normal file
201
MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs
Normal file
@@ -0,0 +1,201 @@
|
||||
using BDInfo;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Text;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.BdInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Class BdInfoExaminer
|
||||
/// </summary>
|
||||
public class BdInfoExaminer : IBlurayExaminer
|
||||
{
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly ITextEncoding _textEncoding;
|
||||
|
||||
public BdInfoExaminer(IFileSystem fileSystem, ITextEncoding textEncoding)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
_textEncoding = textEncoding;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the disc info.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>BlurayDiscInfo.</returns>
|
||||
public BlurayDiscInfo GetDiscInfo(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path))
|
||||
{
|
||||
throw new ArgumentNullException("path");
|
||||
}
|
||||
|
||||
var bdrom = new BDROM(path, _fileSystem, _textEncoding);
|
||||
|
||||
bdrom.Scan();
|
||||
|
||||
// Get the longest playlist
|
||||
var playlist = bdrom.PlaylistFiles.Values.OrderByDescending(p => p.TotalLength).FirstOrDefault(p => p.IsValid);
|
||||
|
||||
var outputStream = new BlurayDiscInfo
|
||||
{
|
||||
MediaStreams = new MediaStream[] {}
|
||||
};
|
||||
|
||||
if (playlist == null)
|
||||
{
|
||||
return outputStream;
|
||||
}
|
||||
|
||||
outputStream.Chapters = playlist.Chapters.ToArray();
|
||||
|
||||
outputStream.RunTimeTicks = TimeSpan.FromSeconds(playlist.TotalLength).Ticks;
|
||||
|
||||
var mediaStreams = new List<MediaStream>();
|
||||
|
||||
foreach (var stream in playlist.SortedStreams)
|
||||
{
|
||||
var videoStream = stream as TSVideoStream;
|
||||
|
||||
if (videoStream != null)
|
||||
{
|
||||
AddVideoStream(mediaStreams, videoStream);
|
||||
continue;
|
||||
}
|
||||
|
||||
var audioStream = stream as TSAudioStream;
|
||||
|
||||
if (audioStream != null)
|
||||
{
|
||||
AddAudioStream(mediaStreams, audioStream);
|
||||
continue;
|
||||
}
|
||||
|
||||
var textStream = stream as TSTextStream;
|
||||
|
||||
if (textStream != null)
|
||||
{
|
||||
AddSubtitleStream(mediaStreams, textStream);
|
||||
continue;
|
||||
}
|
||||
|
||||
var graphicsStream = stream as TSGraphicsStream;
|
||||
|
||||
if (graphicsStream != null)
|
||||
{
|
||||
AddSubtitleStream(mediaStreams, graphicsStream);
|
||||
}
|
||||
}
|
||||
|
||||
outputStream.MediaStreams = mediaStreams.ToArray();
|
||||
|
||||
outputStream.PlaylistName = playlist.Name;
|
||||
|
||||
if (playlist.StreamClips != null && playlist.StreamClips.Any())
|
||||
{
|
||||
// Get the files in the playlist
|
||||
outputStream.Files = playlist.StreamClips.Select(i => i.StreamFile.Name).ToArray();
|
||||
}
|
||||
|
||||
return outputStream;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the video stream.
|
||||
/// </summary>
|
||||
/// <param name="streams">The streams.</param>
|
||||
/// <param name="videoStream">The video stream.</param>
|
||||
private void AddVideoStream(List<MediaStream> streams, TSVideoStream videoStream)
|
||||
{
|
||||
var mediaStream = new MediaStream
|
||||
{
|
||||
BitRate = Convert.ToInt32(videoStream.BitRate),
|
||||
Width = videoStream.Width,
|
||||
Height = videoStream.Height,
|
||||
Codec = videoStream.CodecShortName,
|
||||
IsInterlaced = videoStream.IsInterlaced,
|
||||
Type = MediaStreamType.Video,
|
||||
Index = streams.Count
|
||||
};
|
||||
|
||||
if (videoStream.FrameRateDenominator > 0)
|
||||
{
|
||||
float frameRateEnumerator = videoStream.FrameRateEnumerator;
|
||||
float frameRateDenominator = videoStream.FrameRateDenominator;
|
||||
|
||||
mediaStream.AverageFrameRate = mediaStream.RealFrameRate = frameRateEnumerator / frameRateDenominator;
|
||||
}
|
||||
|
||||
streams.Add(mediaStream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the audio stream.
|
||||
/// </summary>
|
||||
/// <param name="streams">The streams.</param>
|
||||
/// <param name="audioStream">The audio stream.</param>
|
||||
private void AddAudioStream(List<MediaStream> streams, TSAudioStream audioStream)
|
||||
{
|
||||
var stream = new MediaStream
|
||||
{
|
||||
Codec = audioStream.CodecShortName,
|
||||
Language = audioStream.LanguageCode,
|
||||
Channels = audioStream.ChannelCount,
|
||||
SampleRate = audioStream.SampleRate,
|
||||
Type = MediaStreamType.Audio,
|
||||
Index = streams.Count
|
||||
};
|
||||
|
||||
var bitrate = Convert.ToInt32(audioStream.BitRate);
|
||||
|
||||
if (bitrate > 0)
|
||||
{
|
||||
stream.BitRate = bitrate;
|
||||
}
|
||||
|
||||
if (audioStream.LFE > 0)
|
||||
{
|
||||
stream.Channels = audioStream.ChannelCount + 1;
|
||||
}
|
||||
|
||||
streams.Add(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the subtitle stream.
|
||||
/// </summary>
|
||||
/// <param name="streams">The streams.</param>
|
||||
/// <param name="textStream">The text stream.</param>
|
||||
private void AddSubtitleStream(List<MediaStream> streams, TSTextStream textStream)
|
||||
{
|
||||
streams.Add(new MediaStream
|
||||
{
|
||||
Language = textStream.LanguageCode,
|
||||
Codec = textStream.CodecShortName,
|
||||
Type = MediaStreamType.Subtitle,
|
||||
Index = streams.Count
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the subtitle stream.
|
||||
/// </summary>
|
||||
/// <param name="streams">The streams.</param>
|
||||
/// <param name="textStream">The text stream.</param>
|
||||
private void AddSubtitleStream(List<MediaStream> streams, TSGraphicsStream textStream)
|
||||
{
|
||||
streams.Add(new MediaStream
|
||||
{
|
||||
Language = textStream.LanguageCode,
|
||||
Codec = textStream.CodecShortName,
|
||||
Type = MediaStreamType.Subtitle,
|
||||
Index = streams.Count
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Model.Configuration;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
using MediaBrowser.Controller.IO;
|
||||
using MediaBrowser.Model.IO;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Configuration
|
||||
{
|
||||
public class EncodingConfigurationFactory : IConfigurationFactory
|
||||
{
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
public EncodingConfigurationFactory(IFileSystem fileSystem)
|
||||
{
|
||||
_fileSystem = fileSystem;
|
||||
}
|
||||
|
||||
public IEnumerable<ConfigurationStore> GetConfigurations()
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
new EncodingConfigurationStore(_fileSystem)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public class EncodingConfigurationStore : ConfigurationStore, IValidatingConfiguration
|
||||
{
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
public EncodingConfigurationStore(IFileSystem fileSystem)
|
||||
{
|
||||
ConfigurationType = typeof(EncodingOptions);
|
||||
Key = "encoding";
|
||||
_fileSystem = fileSystem;
|
||||
}
|
||||
|
||||
public void Validate(object oldConfig, object newConfig)
|
||||
{
|
||||
var oldEncodingConfig = (EncodingOptions)oldConfig;
|
||||
var newEncodingConfig = (EncodingOptions)newConfig;
|
||||
|
||||
var newPath = newEncodingConfig.TranscodingTempPath;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(newPath)
|
||||
&& !string.Equals(oldEncodingConfig.TranscodingTempPath ?? string.Empty, newPath))
|
||||
{
|
||||
// Validate
|
||||
if (!_fileSystem.DirectoryExists(newPath))
|
||||
{
|
||||
throw new FileNotFoundException(string.Format("{0} does not exist.", newPath));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
62
MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs
Normal file
62
MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using System;
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public class AudioEncoder : BaseEncoder
|
||||
{
|
||||
public AudioEncoder(MediaEncoder mediaEncoder, ILogger logger, IServerConfigurationManager configurationManager, IFileSystem fileSystem, IIsoManager isoManager, ILibraryManager libraryManager, ISessionManager sessionManager, ISubtitleEncoder subtitleEncoder, IMediaSourceManager mediaSourceManager, IProcessFactory processFactory) : base(mediaEncoder, logger, configurationManager, fileSystem, isoManager, libraryManager, sessionManager, subtitleEncoder, mediaSourceManager, processFactory)
|
||||
{
|
||||
}
|
||||
|
||||
protected override string GetCommandLineArguments(EncodingJob state)
|
||||
{
|
||||
var encodingOptions = GetEncodingOptions();
|
||||
|
||||
return EncodingHelper.GetProgressiveAudioFullCommandLine(state, encodingOptions, state.OutputFilePath);
|
||||
}
|
||||
|
||||
protected override string GetOutputFileExtension(EncodingJob state)
|
||||
{
|
||||
var ext = base.GetOutputFileExtension(state);
|
||||
|
||||
if (!string.IsNullOrEmpty(ext))
|
||||
{
|
||||
return ext;
|
||||
}
|
||||
|
||||
var audioCodec = state.Options.AudioCodec;
|
||||
|
||||
if (string.Equals("aac", audioCodec, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".aac";
|
||||
}
|
||||
if (string.Equals("mp3", audioCodec, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".mp3";
|
||||
}
|
||||
if (string.Equals("vorbis", audioCodec, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".ogg";
|
||||
}
|
||||
if (string.Equals("wma", audioCodec, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".wma";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected override bool IsVideoEncoder
|
||||
{
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
375
MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
Normal file
375
MediaBrowser.MediaEncoding/Encoder/BaseEncoder.cs
Normal file
@@ -0,0 +1,375 @@
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Configuration;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public abstract class BaseEncoder
|
||||
{
|
||||
protected readonly MediaEncoder MediaEncoder;
|
||||
protected readonly ILogger Logger;
|
||||
protected readonly IServerConfigurationManager ConfigurationManager;
|
||||
protected readonly IFileSystem FileSystem;
|
||||
protected readonly IIsoManager IsoManager;
|
||||
protected readonly ILibraryManager LibraryManager;
|
||||
protected readonly ISessionManager SessionManager;
|
||||
protected readonly ISubtitleEncoder SubtitleEncoder;
|
||||
protected readonly IMediaSourceManager MediaSourceManager;
|
||||
protected IProcessFactory ProcessFactory;
|
||||
|
||||
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
|
||||
|
||||
protected EncodingHelper EncodingHelper;
|
||||
|
||||
protected BaseEncoder(MediaEncoder mediaEncoder,
|
||||
ILogger logger,
|
||||
IServerConfigurationManager configurationManager,
|
||||
IFileSystem fileSystem,
|
||||
IIsoManager isoManager,
|
||||
ILibraryManager libraryManager,
|
||||
ISessionManager sessionManager,
|
||||
ISubtitleEncoder subtitleEncoder,
|
||||
IMediaSourceManager mediaSourceManager, IProcessFactory processFactory)
|
||||
{
|
||||
MediaEncoder = mediaEncoder;
|
||||
Logger = logger;
|
||||
ConfigurationManager = configurationManager;
|
||||
FileSystem = fileSystem;
|
||||
IsoManager = isoManager;
|
||||
LibraryManager = libraryManager;
|
||||
SessionManager = sessionManager;
|
||||
SubtitleEncoder = subtitleEncoder;
|
||||
MediaSourceManager = mediaSourceManager;
|
||||
ProcessFactory = processFactory;
|
||||
|
||||
EncodingHelper = new EncodingHelper(MediaEncoder, FileSystem, SubtitleEncoder);
|
||||
}
|
||||
|
||||
public async Task<EncodingJob> Start(EncodingJobOptions options,
|
||||
IProgress<double> progress,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var encodingJob = await new EncodingJobFactory(Logger, LibraryManager, MediaSourceManager, ConfigurationManager, MediaEncoder)
|
||||
.CreateJob(options, EncodingHelper, IsVideoEncoder, progress, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
encodingJob.OutputFilePath = GetOutputFilePath(encodingJob);
|
||||
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(encodingJob.OutputFilePath));
|
||||
|
||||
encodingJob.ReadInputAtNativeFramerate = options.ReadInputAtNativeFramerate;
|
||||
|
||||
await AcquireResources(encodingJob, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var commandLineArgs = GetCommandLineArguments(encodingJob);
|
||||
|
||||
var process = ProcessFactory.Create(new ProcessOptions
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false,
|
||||
|
||||
// Must consume both stdout and stderr or deadlocks may occur
|
||||
//RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
RedirectStandardInput = true,
|
||||
|
||||
FileName = MediaEncoder.EncoderPath,
|
||||
Arguments = commandLineArgs,
|
||||
|
||||
IsHidden = true,
|
||||
ErrorDialog = false,
|
||||
EnableRaisingEvents = true
|
||||
});
|
||||
|
||||
var workingDirectory = GetWorkingDirectory(options);
|
||||
if (!string.IsNullOrWhiteSpace(workingDirectory))
|
||||
{
|
||||
process.StartInfo.WorkingDirectory = workingDirectory;
|
||||
}
|
||||
|
||||
OnTranscodeBeginning(encodingJob);
|
||||
|
||||
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
|
||||
Logger.Info(commandLineLogMessage);
|
||||
|
||||
var logFilePath = Path.Combine(ConfigurationManager.CommonApplicationPaths.LogDirectoryPath, "transcode-" + Guid.NewGuid() + ".txt");
|
||||
FileSystem.CreateDirectory(FileSystem.GetDirectoryName(logFilePath));
|
||||
|
||||
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
|
||||
encodingJob.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
|
||||
|
||||
var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(commandLineLogMessage + Environment.NewLine + Environment.NewLine);
|
||||
await encodingJob.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
process.Exited += (sender, args) => OnFfMpegProcessExited(process, encodingJob);
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.ErrorException("Error starting ffmpeg", ex);
|
||||
|
||||
OnTranscodeFailedToStart(encodingJob.OutputFilePath, encodingJob);
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
cancellationToken.Register(() => Cancel(process, encodingJob));
|
||||
|
||||
// MUST read both stdout and stderr asynchronously or a deadlock may occurr
|
||||
//process.BeginOutputReadLine();
|
||||
|
||||
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
|
||||
new JobLogger(Logger).StartStreamingLog(encodingJob, process.StandardError.BaseStream, encodingJob.LogFileStream);
|
||||
|
||||
// Wait for the file to exist before proceeeding
|
||||
while (!FileSystem.FileExists(encodingJob.OutputFilePath) && !encodingJob.HasExited)
|
||||
{
|
||||
await Task.Delay(100, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return encodingJob;
|
||||
}
|
||||
|
||||
private void Cancel(IProcess process, EncodingJob job)
|
||||
{
|
||||
Logger.Info("Killing ffmpeg process for {0}", job.OutputFilePath);
|
||||
|
||||
//process.Kill();
|
||||
process.StandardInput.WriteLine("q");
|
||||
|
||||
job.IsCancelled = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Processes the exited.
|
||||
/// </summary>
|
||||
/// <param name="process">The process.</param>
|
||||
/// <param name="job">The job.</param>
|
||||
private void OnFfMpegProcessExited(IProcess process, EncodingJob job)
|
||||
{
|
||||
job.HasExited = true;
|
||||
|
||||
Logger.Debug("Disposing stream resources");
|
||||
job.Dispose();
|
||||
|
||||
var isSuccesful = false;
|
||||
|
||||
try
|
||||
{
|
||||
var exitCode = process.ExitCode;
|
||||
Logger.Info("FFMpeg exited with code {0}", exitCode);
|
||||
|
||||
isSuccesful = exitCode == 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Logger.Error("FFMpeg exited with an error.");
|
||||
}
|
||||
|
||||
if (isSuccesful && !job.IsCancelled)
|
||||
{
|
||||
job.TaskCompletionSource.TrySetResult(true);
|
||||
}
|
||||
else if (job.IsCancelled)
|
||||
{
|
||||
try
|
||||
{
|
||||
DeleteFiles(job);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
job.TaskCompletionSource.TrySetException(new OperationCanceledException());
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
DeleteFiles(job);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
try
|
||||
{
|
||||
job.TaskCompletionSource.TrySetException(new Exception("Encoding failed"));
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
// This causes on exited to be called twice:
|
||||
//try
|
||||
//{
|
||||
// // Dispose the process
|
||||
// process.Dispose();
|
||||
//}
|
||||
//catch (Exception ex)
|
||||
//{
|
||||
// Logger.ErrorException("Error disposing ffmpeg.", ex);
|
||||
//}
|
||||
}
|
||||
|
||||
protected virtual void DeleteFiles(EncodingJob job)
|
||||
{
|
||||
FileSystem.DeleteFile(job.OutputFilePath);
|
||||
}
|
||||
|
||||
private void OnTranscodeBeginning(EncodingJob job)
|
||||
{
|
||||
job.ReportTranscodingProgress(null, null, null, null, null);
|
||||
}
|
||||
|
||||
private void OnTranscodeFailedToStart(string path, EncodingJob job)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(job.Options.DeviceId))
|
||||
{
|
||||
SessionManager.ClearTranscodingInfo(job.Options.DeviceId);
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract bool IsVideoEncoder { get; }
|
||||
|
||||
protected virtual string GetWorkingDirectory(EncodingJobOptions options)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
protected EncodingOptions GetEncodingOptions()
|
||||
{
|
||||
return ConfigurationManager.GetConfiguration<EncodingOptions>("encoding");
|
||||
}
|
||||
|
||||
protected abstract string GetCommandLineArguments(EncodingJob job);
|
||||
|
||||
private string GetOutputFilePath(EncodingJob state)
|
||||
{
|
||||
var folder = string.IsNullOrWhiteSpace(state.Options.TempDirectory) ?
|
||||
ConfigurationManager.ApplicationPaths.TranscodingTempPath :
|
||||
state.Options.TempDirectory;
|
||||
|
||||
var outputFileExtension = GetOutputFileExtension(state);
|
||||
|
||||
var filename = state.Id + (outputFileExtension ?? string.Empty).ToLower();
|
||||
return Path.Combine(folder, filename);
|
||||
}
|
||||
|
||||
protected virtual string GetOutputFileExtension(EncodingJob state)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(state.Options.Container))
|
||||
{
|
||||
return "." + state.Options.Container;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the output video codec
|
||||
/// </summary>
|
||||
/// <param name="state">The state.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
protected string GetVideoDecoder(EncodingJob state)
|
||||
{
|
||||
if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Only use alternative encoders for video files.
|
||||
// When using concat with folder rips, if the mfx session fails to initialize, ffmpeg will be stuck retrying and will not exit gracefully
|
||||
// Since transcoding of folder rips is expiremental anyway, it's not worth adding additional variables such as this.
|
||||
if (state.VideoType != VideoType.VideoFile)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (state.VideoStream != null && !string.IsNullOrWhiteSpace(state.VideoStream.Codec))
|
||||
{
|
||||
if (string.Equals(GetEncodingOptions().HardwareAccelerationType, "qsv", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
switch (state.MediaSource.VideoStream.Codec.ToLower())
|
||||
{
|
||||
case "avc":
|
||||
case "h264":
|
||||
if (MediaEncoder.SupportsDecoder("h264_qsv"))
|
||||
{
|
||||
// Seeing stalls and failures with decoding. Not worth it compared to encoding.
|
||||
return "-c:v h264_qsv ";
|
||||
}
|
||||
break;
|
||||
case "mpeg2video":
|
||||
if (MediaEncoder.SupportsDecoder("mpeg2_qsv"))
|
||||
{
|
||||
return "-c:v mpeg2_qsv ";
|
||||
}
|
||||
break;
|
||||
case "vc1":
|
||||
if (MediaEncoder.SupportsDecoder("vc1_qsv"))
|
||||
{
|
||||
return "-c:v vc1_qsv ";
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// leave blank so ffmpeg will decide
|
||||
return null;
|
||||
}
|
||||
|
||||
private async Task AcquireResources(EncodingJob state, CancellationToken cancellationToken)
|
||||
{
|
||||
if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
|
||||
{
|
||||
state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Options.LiveStreamId))
|
||||
{
|
||||
var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
|
||||
{
|
||||
OpenToken = state.MediaSource.OpenToken
|
||||
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, null);
|
||||
|
||||
if (state.IsVideoRequest)
|
||||
{
|
||||
EncodingHelper.TryStreamCopy(state);
|
||||
}
|
||||
}
|
||||
|
||||
if (state.MediaSource.BufferMs.HasValue)
|
||||
{
|
||||
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
219
MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
Normal file
219
MediaBrowser.MediaEncoding/Encoder/EncoderValidator.cs
Normal file
@@ -0,0 +1,219 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
using MediaBrowser.Model.Logging;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public class EncoderValidator
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly IProcessFactory _processFactory;
|
||||
|
||||
public EncoderValidator(ILogger logger, IProcessFactory processFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_processFactory = processFactory;
|
||||
}
|
||||
|
||||
public Tuple<List<string>, List<string>> Validate(string encoderPath)
|
||||
{
|
||||
_logger.Info("Validating media encoder at {0}", encoderPath);
|
||||
|
||||
var decoders = GetDecoders(encoderPath);
|
||||
var encoders = GetEncoders(encoderPath);
|
||||
|
||||
_logger.Info("Encoder validation complete");
|
||||
|
||||
return new Tuple<List<string>, List<string>>(decoders, encoders);
|
||||
}
|
||||
|
||||
public bool ValidateVersion(string encoderAppPath, bool logOutput)
|
||||
{
|
||||
string output = string.Empty;
|
||||
try
|
||||
{
|
||||
output = GetProcessOutput(encoderAppPath, "-version");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (logOutput)
|
||||
{
|
||||
_logger.ErrorException("Error validating encoder", ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(output))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_logger.Info("ffmpeg info: {0}", output);
|
||||
|
||||
if (output.IndexOf("Libav developers", StringComparison.OrdinalIgnoreCase) != -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
output = " " + output + " ";
|
||||
|
||||
for (var i = 2013; i <= 2015; i++)
|
||||
{
|
||||
var yearString = i.ToString(CultureInfo.InvariantCulture);
|
||||
if (output.IndexOf(" " + yearString + " ", StringComparison.OrdinalIgnoreCase) != -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private List<string> GetDecoders(string encoderAppPath)
|
||||
{
|
||||
string output = string.Empty;
|
||||
try
|
||||
{
|
||||
output = GetProcessOutput(encoderAppPath, "-decoders");
|
||||
}
|
||||
catch (Exception )
|
||||
{
|
||||
//_logger.ErrorException("Error detecting available decoders", ex);
|
||||
}
|
||||
|
||||
var found = new List<string>();
|
||||
var required = new[]
|
||||
{
|
||||
"mpeg2video",
|
||||
"h264_qsv",
|
||||
"hevc_qsv",
|
||||
"mpeg2_qsv",
|
||||
"vc1_qsv",
|
||||
"h264_cuvid",
|
||||
"hevc_cuvid",
|
||||
"dts",
|
||||
"ac3",
|
||||
"aac",
|
||||
"mp3",
|
||||
"h264",
|
||||
"hevc"
|
||||
};
|
||||
|
||||
foreach (var codec in required)
|
||||
{
|
||||
var srch = " " + codec + " ";
|
||||
|
||||
if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1)
|
||||
{
|
||||
_logger.Info("Decoder available: " + codec);
|
||||
found.Add(codec);
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
private List<string> GetEncoders(string encoderAppPath)
|
||||
{
|
||||
string output = null;
|
||||
try
|
||||
{
|
||||
output = GetProcessOutput(encoderAppPath, "-encoders");
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
|
||||
var found = new List<string>();
|
||||
var required = new[]
|
||||
{
|
||||
"libx264",
|
||||
"libx265",
|
||||
"mpeg4",
|
||||
"msmpeg4",
|
||||
"libvpx",
|
||||
"libvpx-vp9",
|
||||
"aac",
|
||||
"libmp3lame",
|
||||
"libopus",
|
||||
"libvorbis",
|
||||
"srt",
|
||||
"h264_nvenc",
|
||||
"hevc_nvenc",
|
||||
"h264_qsv",
|
||||
"hevc_qsv",
|
||||
"h264_omx",
|
||||
"hevc_omx",
|
||||
"h264_vaapi",
|
||||
"hevc_vaapi",
|
||||
"ac3"
|
||||
};
|
||||
|
||||
output = output ?? string.Empty;
|
||||
|
||||
var index = 0;
|
||||
|
||||
foreach (var codec in required)
|
||||
{
|
||||
var srch = " " + codec + " ";
|
||||
|
||||
if (output.IndexOf(srch, StringComparison.OrdinalIgnoreCase) != -1)
|
||||
{
|
||||
if (index < required.Length - 1)
|
||||
{
|
||||
_logger.Info("Encoder available: " + codec);
|
||||
}
|
||||
|
||||
found.Add(codec);
|
||||
}
|
||||
index++;
|
||||
}
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
private string GetProcessOutput(string path, string arguments)
|
||||
{
|
||||
var process = _processFactory.Create(new ProcessOptions
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false,
|
||||
FileName = path,
|
||||
Arguments = arguments,
|
||||
IsHidden = true,
|
||||
ErrorDialog = false,
|
||||
RedirectStandardOutput = true
|
||||
});
|
||||
|
||||
_logger.Info("Running {0} {1}", path, arguments);
|
||||
|
||||
using (process)
|
||||
{
|
||||
process.Start();
|
||||
|
||||
try
|
||||
{
|
||||
return process.StandardOutput.ReadToEnd();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_logger.Info("Killing process {0} {1}", path, arguments);
|
||||
|
||||
// Hate having to do this
|
||||
try
|
||||
{
|
||||
process.Kill();
|
||||
}
|
||||
catch (Exception ex1)
|
||||
{
|
||||
_logger.ErrorException("Error killing process", ex1);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
197
MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
Normal file
197
MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs
Normal file
@@ -0,0 +1,197 @@
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Drawing;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Net;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public class EncodingJob : EncodingJobInfo, IDisposable
|
||||
{
|
||||
public bool HasExited { get; internal set; }
|
||||
public bool IsCancelled { get; internal set; }
|
||||
|
||||
public Stream LogFileStream { get; set; }
|
||||
public IProgress<double> Progress { get; set; }
|
||||
public TaskCompletionSource<bool> TaskCompletionSource;
|
||||
|
||||
public EncodingJobOptions Options
|
||||
{
|
||||
get { return (EncodingJobOptions) BaseRequest; }
|
||||
set { BaseRequest = value; }
|
||||
}
|
||||
|
||||
public string Id { get; set; }
|
||||
|
||||
public string MimeType { get; set; }
|
||||
public bool EstimateContentLength { get; set; }
|
||||
public TranscodeSeekInfo TranscodeSeekInfo { get; set; }
|
||||
public long? EncodingDurationTicks { get; set; }
|
||||
|
||||
public string ItemType { get; set; }
|
||||
|
||||
public string GetMimeType(string outputPath)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(MimeType))
|
||||
{
|
||||
return MimeType;
|
||||
}
|
||||
|
||||
return MimeTypes.GetMimeType(outputPath);
|
||||
}
|
||||
|
||||
private readonly ILogger _logger;
|
||||
private readonly IMediaSourceManager _mediaSourceManager;
|
||||
|
||||
public EncodingJob(ILogger logger, IMediaSourceManager mediaSourceManager) :
|
||||
base(logger, mediaSourceManager, TranscodingJobType.Progressive)
|
||||
{
|
||||
_logger = logger;
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
Id = Guid.NewGuid().ToString("N");
|
||||
|
||||
_logger = logger;
|
||||
TaskCompletionSource = new TaskCompletionSource<bool>();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
DisposeLiveStream();
|
||||
DisposeLogStream();
|
||||
DisposeIsoMount();
|
||||
}
|
||||
|
||||
private void DisposeLogStream()
|
||||
{
|
||||
if (LogFileStream != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogFileStream.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error disposing log stream", ex);
|
||||
}
|
||||
|
||||
LogFileStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
private async void DisposeLiveStream()
|
||||
{
|
||||
if (MediaSource.RequiresClosing && string.IsNullOrWhiteSpace(Options.LiveStreamId) && !string.IsNullOrWhiteSpace(MediaSource.LiveStreamId))
|
||||
{
|
||||
try
|
||||
{
|
||||
await _mediaSourceManager.CloseLiveStream(MediaSource.LiveStreamId).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error closing media source", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public string OutputFilePath { get; set; }
|
||||
|
||||
public string ActualOutputVideoCodec
|
||||
{
|
||||
get
|
||||
{
|
||||
var codec = OutputVideoCodec;
|
||||
|
||||
if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var stream = VideoStream;
|
||||
|
||||
if (stream != null)
|
||||
{
|
||||
return stream.Codec;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return codec;
|
||||
}
|
||||
}
|
||||
|
||||
public string ActualOutputAudioCodec
|
||||
{
|
||||
get
|
||||
{
|
||||
var codec = OutputAudioCodec;
|
||||
|
||||
if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var stream = AudioStream;
|
||||
|
||||
if (stream != null)
|
||||
{
|
||||
return stream.Codec;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return codec;
|
||||
}
|
||||
}
|
||||
|
||||
public void ReportTranscodingProgress(TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded, int? bitRate)
|
||||
{
|
||||
var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
|
||||
|
||||
// job.Framerate = framerate;
|
||||
|
||||
if (!percentComplete.HasValue && ticks.HasValue && RunTimeTicks.HasValue)
|
||||
{
|
||||
var pct = ticks.Value / RunTimeTicks.Value;
|
||||
percentComplete = pct * 100;
|
||||
}
|
||||
|
||||
if (percentComplete.HasValue)
|
||||
{
|
||||
Progress.Report(percentComplete.Value);
|
||||
}
|
||||
|
||||
// job.TranscodingPositionTicks = ticks;
|
||||
// job.BytesTranscoded = bytesTranscoded;
|
||||
|
||||
var deviceId = Options.DeviceId;
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(deviceId))
|
||||
{
|
||||
var audioCodec = ActualOutputVideoCodec;
|
||||
var videoCodec = ActualOutputVideoCodec;
|
||||
|
||||
// SessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
|
||||
// {
|
||||
// Bitrate = job.TotalOutputBitrate,
|
||||
// AudioCodec = audioCodec,
|
||||
// VideoCodec = videoCodec,
|
||||
// Container = job.Options.OutputContainer,
|
||||
// Framerate = framerate,
|
||||
// CompletionPercentage = percentComplete,
|
||||
// Width = job.OutputWidth,
|
||||
// Height = job.OutputHeight,
|
||||
// AudioChannels = job.OutputAudioChannels,
|
||||
// IsAudioDirect = string.Equals(job.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase),
|
||||
// IsVideoDirect = string.Equals(job.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
|
||||
// });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
309
MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs
Normal file
309
MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs
Normal file
@@ -0,0 +1,309 @@
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Model.Configuration;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public class EncodingJobFactory
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly IMediaSourceManager _mediaSourceManager;
|
||||
private readonly IConfigurationManager _config;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
|
||||
protected static readonly CultureInfo UsCulture = new CultureInfo("en-US");
|
||||
|
||||
public EncodingJobFactory(ILogger logger, ILibraryManager libraryManager, IMediaSourceManager mediaSourceManager, IConfigurationManager config, IMediaEncoder mediaEncoder)
|
||||
{
|
||||
_logger = logger;
|
||||
_libraryManager = libraryManager;
|
||||
_mediaSourceManager = mediaSourceManager;
|
||||
_config = config;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
}
|
||||
|
||||
public async Task<EncodingJob> CreateJob(EncodingJobOptions options, EncodingHelper encodingHelper, bool isVideoRequest, IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
var request = options;
|
||||
|
||||
if (string.IsNullOrEmpty(request.AudioCodec))
|
||||
{
|
||||
request.AudioCodec = InferAudioCodec(request.Container);
|
||||
}
|
||||
|
||||
var state = new EncodingJob(_logger, _mediaSourceManager)
|
||||
{
|
||||
Options = options,
|
||||
IsVideoRequest = isVideoRequest,
|
||||
Progress = progress
|
||||
};
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.VideoCodec))
|
||||
{
|
||||
state.SupportedVideoCodecs = request.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
|
||||
request.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.AudioCodec))
|
||||
{
|
||||
state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
|
||||
request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault();
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
|
||||
{
|
||||
state.SupportedSubtitleCodecs = request.SubtitleCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();
|
||||
request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(i => _mediaEncoder.CanEncodeToSubtitleCodec(i))
|
||||
?? state.SupportedSubtitleCodecs.FirstOrDefault();
|
||||
}
|
||||
|
||||
var item = _libraryManager.GetItemById(request.Id);
|
||||
state.ItemType = item.GetType().Name;
|
||||
|
||||
state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
// TODO
|
||||
// var primaryImage = item.GetImageInfo(ImageType.Primary, 0) ??
|
||||
// item.Parents.Select(i => i.GetImageInfo(ImageType.Primary, 0)).FirstOrDefault(i => i != null);
|
||||
|
||||
// if (primaryImage != null)
|
||||
// {
|
||||
// state.AlbumCoverPath = primaryImage.Path;
|
||||
// }
|
||||
|
||||
// TODO network path substition useful ?
|
||||
var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, null, true, true, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
|
||||
? mediaSources.First()
|
||||
: mediaSources.First(i => string.Equals(i.Id, request.MediaSourceId));
|
||||
|
||||
var videoRequest = state.Options;
|
||||
|
||||
encodingHelper.AttachMediaSourceInfo(state, mediaSource, null);
|
||||
|
||||
//var container = Path.GetExtension(state.RequestedUrl);
|
||||
|
||||
//if (string.IsNullOrEmpty(container))
|
||||
//{
|
||||
// container = request.Static ?
|
||||
// state.InputContainer :
|
||||
// (Path.GetExtension(GetOutputFilePath(state)) ?? string.Empty).TrimStart('.');
|
||||
//}
|
||||
|
||||
//state.OutputContainer = (container ?? string.Empty).TrimStart('.');
|
||||
|
||||
state.OutputAudioBitrate = encodingHelper.GetAudioBitrateParam(state.Options, state.AudioStream);
|
||||
|
||||
state.OutputAudioCodec = state.Options.AudioCodec;
|
||||
|
||||
state.OutputAudioChannels = encodingHelper.GetNumAudioChannelsParam(state, state.AudioStream, state.OutputAudioCodec);
|
||||
|
||||
if (videoRequest != null)
|
||||
{
|
||||
state.OutputVideoCodec = state.Options.VideoCodec;
|
||||
state.OutputVideoBitrate = encodingHelper.GetVideoBitrateParamValue(state.Options, state.VideoStream, state.OutputVideoCodec);
|
||||
|
||||
if (state.OutputVideoBitrate.HasValue)
|
||||
{
|
||||
var resolution = ResolutionNormalizer.Normalize(
|
||||
state.VideoStream == null ? (int?)null : state.VideoStream.BitRate,
|
||||
state.VideoStream == null ? (int?)null : state.VideoStream.Width,
|
||||
state.VideoStream == null ? (int?)null : state.VideoStream.Height,
|
||||
state.OutputVideoBitrate.Value,
|
||||
state.VideoStream == null ? null : state.VideoStream.Codec,
|
||||
state.OutputVideoCodec,
|
||||
videoRequest.MaxWidth,
|
||||
videoRequest.MaxHeight);
|
||||
|
||||
videoRequest.MaxWidth = resolution.MaxWidth;
|
||||
videoRequest.MaxHeight = resolution.MaxHeight;
|
||||
}
|
||||
}
|
||||
|
||||
ApplyDeviceProfileSettings(state);
|
||||
|
||||
if (videoRequest != null)
|
||||
{
|
||||
encodingHelper.TryStreamCopy(state);
|
||||
}
|
||||
|
||||
//state.OutputFilePath = GetOutputFilePath(state);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
protected EncodingOptions GetEncodingOptions()
|
||||
{
|
||||
return _config.GetConfiguration<EncodingOptions>("encoding");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Infers the video codec.
|
||||
/// </summary>
|
||||
/// <param name="container">The container.</param>
|
||||
/// <returns>System.Nullable{VideoCodecs}.</returns>
|
||||
private static string InferVideoCodec(string container)
|
||||
{
|
||||
var ext = "." + (container ?? string.Empty);
|
||||
|
||||
if (string.Equals(ext, ".asf", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "wmv";
|
||||
}
|
||||
if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "vpx";
|
||||
}
|
||||
if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "theora";
|
||||
}
|
||||
if (string.Equals(ext, ".m3u8", StringComparison.OrdinalIgnoreCase) || string.Equals(ext, ".ts", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "h264";
|
||||
}
|
||||
|
||||
return "copy";
|
||||
}
|
||||
|
||||
private string InferAudioCodec(string container)
|
||||
{
|
||||
var ext = "." + (container ?? string.Empty);
|
||||
|
||||
if (string.Equals(ext, ".mp3", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "mp3";
|
||||
}
|
||||
if (string.Equals(ext, ".aac", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "aac";
|
||||
}
|
||||
if (string.Equals(ext, ".wma", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "wma";
|
||||
}
|
||||
if (string.Equals(ext, ".ogg", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "vorbis";
|
||||
}
|
||||
if (string.Equals(ext, ".oga", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "vorbis";
|
||||
}
|
||||
if (string.Equals(ext, ".ogv", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "vorbis";
|
||||
}
|
||||
if (string.Equals(ext, ".webm", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "vorbis";
|
||||
}
|
||||
if (string.Equals(ext, ".webma", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return "vorbis";
|
||||
}
|
||||
|
||||
return "copy";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the specified stream is H264.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream.</param>
|
||||
/// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
|
||||
protected bool IsH264(MediaStream stream)
|
||||
{
|
||||
var codec = stream.Codec ?? string.Empty;
|
||||
|
||||
return codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
|
||||
codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
|
||||
}
|
||||
|
||||
private static int GetVideoProfileScore(string profile)
|
||||
{
|
||||
var list = new List<string>
|
||||
{
|
||||
"Constrained Baseline",
|
||||
"Baseline",
|
||||
"Extended",
|
||||
"Main",
|
||||
"High",
|
||||
"Progressive High",
|
||||
"Constrained High"
|
||||
};
|
||||
|
||||
return Array.FindIndex(list.ToArray(), t => string.Equals(t, profile, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private void ApplyDeviceProfileSettings(EncodingJob state)
|
||||
{
|
||||
var profile = state.Options.DeviceProfile;
|
||||
|
||||
if (profile == null)
|
||||
{
|
||||
// Don't use settings from the default profile.
|
||||
// Only use a specific profile if it was requested.
|
||||
return;
|
||||
}
|
||||
|
||||
var audioCodec = state.ActualOutputAudioCodec;
|
||||
|
||||
var videoCodec = state.ActualOutputVideoCodec;
|
||||
var outputContainer = state.Options.Container;
|
||||
|
||||
var mediaProfile = state.IsVideoRequest ?
|
||||
profile.GetAudioMediaProfile(outputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate, state.OutputAudioSampleRate, state.OutputAudioBitDepth) :
|
||||
profile.GetVideoMediaProfile(outputContainer,
|
||||
audioCodec,
|
||||
videoCodec,
|
||||
state.OutputWidth,
|
||||
state.OutputHeight,
|
||||
state.TargetVideoBitDepth,
|
||||
state.OutputVideoBitrate,
|
||||
state.TargetVideoProfile,
|
||||
state.TargetVideoLevel,
|
||||
state.TargetFramerate,
|
||||
state.TargetPacketLength,
|
||||
state.TargetTimestamp,
|
||||
state.IsTargetAnamorphic,
|
||||
state.IsTargetInterlaced,
|
||||
state.TargetRefFrames,
|
||||
state.TargetVideoStreamCount,
|
||||
state.TargetAudioStreamCount,
|
||||
state.TargetVideoCodecTag,
|
||||
state.IsTargetAVC);
|
||||
|
||||
if (mediaProfile != null)
|
||||
{
|
||||
state.MimeType = mediaProfile.MimeType;
|
||||
}
|
||||
|
||||
var transcodingProfile = state.IsVideoRequest ?
|
||||
profile.GetAudioTranscodingProfile(outputContainer, audioCodec) :
|
||||
profile.GetVideoTranscodingProfile(outputContainer, audioCodec, videoCodec);
|
||||
|
||||
if (transcodingProfile != null)
|
||||
{
|
||||
state.EstimateContentLength = transcodingProfile.EstimateContentLength;
|
||||
//state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
|
||||
state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
|
||||
|
||||
state.Options.CopyTimestamps = transcodingProfile.CopyTimestamps;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
70
MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs
Normal file
70
MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs
Normal file
@@ -0,0 +1,70 @@
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public static class EncodingUtils
|
||||
{
|
||||
public static string GetInputArgument(List<string> inputFiles, MediaProtocol protocol)
|
||||
{
|
||||
if (protocol != MediaProtocol.File)
|
||||
{
|
||||
var url = inputFiles.First();
|
||||
|
||||
return string.Format("\"{0}\"", url);
|
||||
}
|
||||
|
||||
return GetConcatInputArgument(inputFiles);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the concat input argument.
|
||||
/// </summary>
|
||||
/// <param name="inputFiles">The input files.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
private static string GetConcatInputArgument(IReadOnlyList<string> inputFiles)
|
||||
{
|
||||
// Get all streams
|
||||
// If there's more than one we'll need to use the concat command
|
||||
if (inputFiles.Count > 1)
|
||||
{
|
||||
var files = string.Join("|", inputFiles.Select(NormalizePath).ToArray());
|
||||
|
||||
return string.Format("concat:\"{0}\"", files);
|
||||
}
|
||||
|
||||
// Determine the input path for video files
|
||||
return GetFileInputArgument(inputFiles[0]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the file input argument.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
private static string GetFileInputArgument(string path)
|
||||
{
|
||||
if (path.IndexOf("://") != -1)
|
||||
{
|
||||
return string.Format("\"{0}\"", path);
|
||||
}
|
||||
|
||||
// Quotes are valid path characters in linux and they need to be escaped here with a leading \
|
||||
path = NormalizePath(path);
|
||||
|
||||
return string.Format("file:\"{0}\"", path);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes the path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
private static string NormalizePath(string path)
|
||||
{
|
||||
// Quotes are valid path characters in linux and they need to be escaped here with a leading \
|
||||
return path.Replace("\"", "\\\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
182
MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs
Normal file
182
MediaBrowser.MediaEncoding/Encoder/FontConfigLoader.cs
Normal file
@@ -0,0 +1,182 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Common.Progress;
|
||||
using MediaBrowser.Controller.IO;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.Net;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public class FontConfigLoader
|
||||
{
|
||||
private readonly IHttpClient _httpClient;
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
private readonly ILogger _logger;
|
||||
private readonly IZipClient _zipClient;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
private readonly string[] _fontUrls =
|
||||
{
|
||||
"https://github.com/MediaBrowser/MediaBrowser.Resources/raw/master/ffmpeg/ARIALUNI.7z"
|
||||
};
|
||||
|
||||
public FontConfigLoader(IHttpClient httpClient, IApplicationPaths appPaths, ILogger logger, IZipClient zipClient, IFileSystem fileSystem)
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_appPaths = appPaths;
|
||||
_logger = logger;
|
||||
_zipClient = zipClient;
|
||||
_fileSystem = fileSystem;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the fonts.
|
||||
/// </summary>
|
||||
/// <param name="targetPath">The target path.</param>
|
||||
/// <returns>Task.</returns>
|
||||
public async Task DownloadFonts(string targetPath)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fontsDirectory = Path.Combine(targetPath, "fonts");
|
||||
|
||||
_fileSystem.CreateDirectory(fontsDirectory);
|
||||
|
||||
const string fontFilename = "ARIALUNI.TTF";
|
||||
|
||||
var fontFile = Path.Combine(fontsDirectory, fontFilename);
|
||||
|
||||
if (_fileSystem.FileExists(fontFile))
|
||||
{
|
||||
await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Kick this off, but no need to wait on it
|
||||
var task = Task.Run(async () =>
|
||||
{
|
||||
await DownloadFontFile(fontsDirectory, fontFilename, new SimpleProgress<double>()).ConfigureAwait(false);
|
||||
|
||||
await WriteFontConfigFile(fontsDirectory).ConfigureAwait(false);
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (HttpException ex)
|
||||
{
|
||||
// Don't let the server crash because of this
|
||||
_logger.ErrorException("Error downloading ffmpeg font files", ex);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Don't let the server crash because of this
|
||||
_logger.ErrorException("Error writing ffmpeg font files", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads the font file.
|
||||
/// </summary>
|
||||
/// <param name="fontsDirectory">The fonts directory.</param>
|
||||
/// <param name="fontFilename">The font filename.</param>
|
||||
/// <returns>Task.</returns>
|
||||
private async Task DownloadFontFile(string fontsDirectory, string fontFilename, IProgress<double> progress)
|
||||
{
|
||||
var existingFile = _fileSystem
|
||||
.GetFilePaths(_appPaths.ProgramDataPath, true)
|
||||
.FirstOrDefault(i => string.Equals(fontFilename, Path.GetFileName(i), StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (existingFile != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
_fileSystem.CopyFile(existingFile, Path.Combine(fontsDirectory, fontFilename), true);
|
||||
return;
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// Log this, but don't let it fail the operation
|
||||
_logger.ErrorException("Error copying file", ex);
|
||||
}
|
||||
}
|
||||
|
||||
string tempFile = null;
|
||||
|
||||
foreach (var url in _fontUrls)
|
||||
{
|
||||
progress.Report(0);
|
||||
|
||||
try
|
||||
{
|
||||
tempFile = await _httpClient.GetTempFile(new HttpRequestOptions
|
||||
{
|
||||
Url = url,
|
||||
Progress = progress
|
||||
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// The core can function without the font file, so handle this
|
||||
_logger.ErrorException("Failed to download ffmpeg font file from {0}", ex, url);
|
||||
}
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(tempFile))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Extract7zArchive(tempFile, fontsDirectory);
|
||||
|
||||
try
|
||||
{
|
||||
_fileSystem.DeleteFile(tempFile);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
// Log this, but don't let it fail the operation
|
||||
_logger.ErrorException("Error deleting temp file {0}", ex, tempFile);
|
||||
}
|
||||
}
|
||||
private void Extract7zArchive(string archivePath, string targetPath)
|
||||
{
|
||||
_logger.Info("Extracting {0} to {1}", archivePath, targetPath);
|
||||
|
||||
_zipClient.ExtractAllFrom7z(archivePath, targetPath, true);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes the font config file.
|
||||
/// </summary>
|
||||
/// <param name="fontsDirectory">The fonts directory.</param>
|
||||
/// <returns>Task.</returns>
|
||||
private async Task WriteFontConfigFile(string fontsDirectory)
|
||||
{
|
||||
const string fontConfigFilename = "fonts.conf";
|
||||
var fontConfigFile = Path.Combine(fontsDirectory, fontConfigFilename);
|
||||
|
||||
if (!_fileSystem.FileExists(fontConfigFile))
|
||||
{
|
||||
var contents = string.Format("<?xml version=\"1.0\"?><fontconfig><dir>{0}</dir><alias><family>Arial</family><prefer>Arial Unicode MS</prefer></alias></fontconfig>", fontsDirectory);
|
||||
|
||||
var bytes = Encoding.UTF8.GetBytes(contents);
|
||||
|
||||
using (var fileStream = _fileSystem.GetFileStream(fontConfigFile, FileOpenMode.Create, FileAccessMode.Write,
|
||||
FileShareMode.Read, true))
|
||||
{
|
||||
await fileStream.WriteAsync(bytes, 0, bytes.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1148
MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
Normal file
1148
MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
Normal file
File diff suppressed because it is too large
Load Diff
66
MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs
Normal file
66
MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using MediaBrowser.Model.Dlna;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Encoder
|
||||
{
|
||||
public class VideoEncoder : BaseEncoder
|
||||
{
|
||||
public VideoEncoder(MediaEncoder mediaEncoder, ILogger logger, IServerConfigurationManager configurationManager, IFileSystem fileSystem, IIsoManager isoManager, ILibraryManager libraryManager, ISessionManager sessionManager, ISubtitleEncoder subtitleEncoder, IMediaSourceManager mediaSourceManager, IProcessFactory processFactory) : base(mediaEncoder, logger, configurationManager, fileSystem, isoManager, libraryManager, sessionManager, subtitleEncoder, mediaSourceManager, processFactory)
|
||||
{
|
||||
}
|
||||
|
||||
protected override string GetCommandLineArguments(EncodingJob state)
|
||||
{
|
||||
// Get the output codec name
|
||||
var encodingOptions = GetEncodingOptions();
|
||||
|
||||
return EncodingHelper.GetProgressiveVideoFullCommandLine(state, encodingOptions, state.OutputFilePath, "superfast");
|
||||
}
|
||||
|
||||
protected override string GetOutputFileExtension(EncodingJob state)
|
||||
{
|
||||
var ext = base.GetOutputFileExtension(state);
|
||||
|
||||
if (!string.IsNullOrEmpty(ext))
|
||||
{
|
||||
return ext;
|
||||
}
|
||||
|
||||
var videoCodec = state.Options.VideoCodec;
|
||||
|
||||
if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".ts";
|
||||
}
|
||||
if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".ogv";
|
||||
}
|
||||
if (string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".webm";
|
||||
}
|
||||
if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ".asf";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected override bool IsVideoEncoder
|
||||
{
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
33
MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
Normal file
33
MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj
Normal file
@@ -0,0 +1,33 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netstandard2.0</TargetFramework>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="..\SharedVersion.cs">
|
||||
<Link>Properties\SharedVersion.cs</Link>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BDInfo\BDInfo.csproj">
|
||||
<Project>{88ae38df-19d7-406f-a6a9-09527719a21e}</Project>
|
||||
<Name>BDInfo</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\MediaBrowser.Common\MediaBrowser.Common.csproj">
|
||||
<Project>{9142eefa-7570-41e1-bfcc-468bb571af2f}</Project>
|
||||
<Name>MediaBrowser.Common</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\MediaBrowser.Controller\MediaBrowser.Controller.csproj">
|
||||
<Project>{17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2}</Project>
|
||||
<Name>MediaBrowser.Controller</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\MediaBrowser.Model\MediaBrowser.Model.csproj">
|
||||
<Project>{7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b}</Project>
|
||||
<Name>MediaBrowser.Model</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\OpenSubtitlesHandler\OpenSubtitlesHandler.csproj">
|
||||
<Project>{4a4402d4-e910-443b-b8fc-2c18286a2ca0}</Project>
|
||||
<Name>OpenSubtitlesHandler</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" standalone="no"?>
|
||||
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Target Name="EmitMSBuildWarning" BeforeTargets="Build">
|
||||
<Warning Text="Packages containing MSBuild targets and props files cannot be fully installed in projects targeting multiple frameworks. The MSBuild targets and props files have been ignored." />
|
||||
</Target>
|
||||
</Project>
|
||||
117
MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs
Normal file
117
MediaBrowser.MediaEncoding/Probing/FFProbeHelpers.cs
Normal file
@@ -0,0 +1,117 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Probing
|
||||
{
|
||||
public static class FFProbeHelpers
|
||||
{
|
||||
/// <summary>
|
||||
/// Normalizes the FF probe result.
|
||||
/// </summary>
|
||||
/// <param name="result">The result.</param>
|
||||
public static void NormalizeFFProbeResult(InternalMediaInfoResult result)
|
||||
{
|
||||
if (result == null)
|
||||
{
|
||||
throw new ArgumentNullException("result");
|
||||
}
|
||||
|
||||
if (result.format != null && result.format.tags != null)
|
||||
{
|
||||
result.format.tags = ConvertDictionaryToCaseInSensitive(result.format.tags);
|
||||
}
|
||||
|
||||
if (result.streams != null)
|
||||
{
|
||||
// Convert all dictionaries to case insensitive
|
||||
foreach (var stream in result.streams)
|
||||
{
|
||||
if (stream.tags != null)
|
||||
{
|
||||
stream.tags = ConvertDictionaryToCaseInSensitive(stream.tags);
|
||||
}
|
||||
|
||||
if (stream.disposition != null)
|
||||
{
|
||||
stream.disposition = ConvertDictionaryToCaseInSensitive(stream.disposition);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a string from an FFProbeResult tags dictionary
|
||||
/// </summary>
|
||||
/// <param name="tags">The tags.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>System.String.</returns>
|
||||
public static string GetDictionaryValue(Dictionary<string, string> tags, string key)
|
||||
{
|
||||
if (tags == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
string val;
|
||||
|
||||
tags.TryGetValue(key, out val);
|
||||
return val;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets an int from an FFProbeResult tags dictionary
|
||||
/// </summary>
|
||||
/// <param name="tags">The tags.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>System.Nullable{System.Int32}.</returns>
|
||||
public static int? GetDictionaryNumericValue(Dictionary<string, string> tags, string key)
|
||||
{
|
||||
var val = GetDictionaryValue(tags, key);
|
||||
|
||||
if (!string.IsNullOrEmpty(val))
|
||||
{
|
||||
int i;
|
||||
|
||||
if (int.TryParse(val, out i))
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a DateTime from an FFProbeResult tags dictionary
|
||||
/// </summary>
|
||||
/// <param name="tags">The tags.</param>
|
||||
/// <param name="key">The key.</param>
|
||||
/// <returns>System.Nullable{DateTime}.</returns>
|
||||
public static DateTime? GetDictionaryDateTime(Dictionary<string, string> tags, string key)
|
||||
{
|
||||
var val = GetDictionaryValue(tags, key);
|
||||
|
||||
if (!string.IsNullOrEmpty(val))
|
||||
{
|
||||
DateTime i;
|
||||
|
||||
if (DateTime.TryParse(val, out i))
|
||||
{
|
||||
return i.ToUniversalTime();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a dictionary to case insensitive
|
||||
/// </summary>
|
||||
/// <param name="dict">The dict.</param>
|
||||
/// <returns>Dictionary{System.StringSystem.String}.</returns>
|
||||
private static Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
|
||||
{
|
||||
return new Dictionary<string, string>(dict, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
}
|
||||
341
MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
Normal file
341
MediaBrowser.MediaEncoding/Probing/InternalMediaInfoResult.cs
Normal file
@@ -0,0 +1,341 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Probing
|
||||
{
|
||||
/// <summary>
|
||||
/// Class MediaInfoResult
|
||||
/// </summary>
|
||||
public class InternalMediaInfoResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the streams.
|
||||
/// </summary>
|
||||
/// <value>The streams.</value>
|
||||
public MediaStreamInfo[] streams { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the format.
|
||||
/// </summary>
|
||||
/// <value>The format.</value>
|
||||
public MediaFormatInfo format { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the chapters.
|
||||
/// </summary>
|
||||
/// <value>The chapters.</value>
|
||||
public MediaChapter[] Chapters { get; set; }
|
||||
}
|
||||
|
||||
public class MediaChapter
|
||||
{
|
||||
public int id { get; set; }
|
||||
public string time_base { get; set; }
|
||||
public long start { get; set; }
|
||||
public string start_time { get; set; }
|
||||
public long end { get; set; }
|
||||
public string end_time { get; set; }
|
||||
public Dictionary<string, string> tags { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Represents a stream within the output
|
||||
/// </summary>
|
||||
public class MediaStreamInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the index.
|
||||
/// </summary>
|
||||
/// <value>The index.</value>
|
||||
public int index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the profile.
|
||||
/// </summary>
|
||||
/// <value>The profile.</value>
|
||||
public string profile { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec_name.
|
||||
/// </summary>
|
||||
/// <value>The codec_name.</value>
|
||||
public string codec_name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec_long_name.
|
||||
/// </summary>
|
||||
/// <value>The codec_long_name.</value>
|
||||
public string codec_long_name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec_type.
|
||||
/// </summary>
|
||||
/// <value>The codec_type.</value>
|
||||
public string codec_type { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sample_rate.
|
||||
/// </summary>
|
||||
/// <value>The sample_rate.</value>
|
||||
public string sample_rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the channels.
|
||||
/// </summary>
|
||||
/// <value>The channels.</value>
|
||||
public int channels { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the channel_layout.
|
||||
/// </summary>
|
||||
/// <value>The channel_layout.</value>
|
||||
public string channel_layout { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the avg_frame_rate.
|
||||
/// </summary>
|
||||
/// <value>The avg_frame_rate.</value>
|
||||
public string avg_frame_rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration.
|
||||
/// </summary>
|
||||
/// <value>The duration.</value>
|
||||
public string duration { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bit_rate.
|
||||
/// </summary>
|
||||
/// <value>The bit_rate.</value>
|
||||
public string bit_rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the width.
|
||||
/// </summary>
|
||||
/// <value>The width.</value>
|
||||
public int width { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the refs.
|
||||
/// </summary>
|
||||
/// <value>The refs.</value>
|
||||
public int refs { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the height.
|
||||
/// </summary>
|
||||
/// <value>The height.</value>
|
||||
public int height { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the display_aspect_ratio.
|
||||
/// </summary>
|
||||
/// <value>The display_aspect_ratio.</value>
|
||||
public string display_aspect_ratio { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
/// <value>The tags.</value>
|
||||
public Dictionary<string, string> tags { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bits_per_sample.
|
||||
/// </summary>
|
||||
/// <value>The bits_per_sample.</value>
|
||||
public int bits_per_sample { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bits_per_raw_sample.
|
||||
/// </summary>
|
||||
/// <value>The bits_per_raw_sample.</value>
|
||||
public int bits_per_raw_sample { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the r_frame_rate.
|
||||
/// </summary>
|
||||
/// <value>The r_frame_rate.</value>
|
||||
public string r_frame_rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the has_b_frames.
|
||||
/// </summary>
|
||||
/// <value>The has_b_frames.</value>
|
||||
public int has_b_frames { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sample_aspect_ratio.
|
||||
/// </summary>
|
||||
/// <value>The sample_aspect_ratio.</value>
|
||||
public string sample_aspect_ratio { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the pix_fmt.
|
||||
/// </summary>
|
||||
/// <value>The pix_fmt.</value>
|
||||
public string pix_fmt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the level.
|
||||
/// </summary>
|
||||
/// <value>The level.</value>
|
||||
public int level { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time_base.
|
||||
/// </summary>
|
||||
/// <value>The time_base.</value>
|
||||
public string time_base { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the start_time.
|
||||
/// </summary>
|
||||
/// <value>The start_time.</value>
|
||||
public string start_time { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec_time_base.
|
||||
/// </summary>
|
||||
/// <value>The codec_time_base.</value>
|
||||
public string codec_time_base { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec_tag.
|
||||
/// </summary>
|
||||
/// <value>The codec_tag.</value>
|
||||
public string codec_tag { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the codec_tag_string.
|
||||
/// </summary>
|
||||
/// <value>The codec_tag_string.</value>
|
||||
public string codec_tag_string { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the sample_fmt.
|
||||
/// </summary>
|
||||
/// <value>The sample_fmt.</value>
|
||||
public string sample_fmt { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the dmix_mode.
|
||||
/// </summary>
|
||||
/// <value>The dmix_mode.</value>
|
||||
public string dmix_mode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the start_pts.
|
||||
/// </summary>
|
||||
/// <value>The start_pts.</value>
|
||||
public string start_pts { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the is_avc.
|
||||
/// </summary>
|
||||
/// <value>The is_avc.</value>
|
||||
public string is_avc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the nal_length_size.
|
||||
/// </summary>
|
||||
/// <value>The nal_length_size.</value>
|
||||
public string nal_length_size { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ltrt_cmixlev.
|
||||
/// </summary>
|
||||
/// <value>The ltrt_cmixlev.</value>
|
||||
public string ltrt_cmixlev { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ltrt_surmixlev.
|
||||
/// </summary>
|
||||
/// <value>The ltrt_surmixlev.</value>
|
||||
public string ltrt_surmixlev { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the loro_cmixlev.
|
||||
/// </summary>
|
||||
/// <value>The loro_cmixlev.</value>
|
||||
public string loro_cmixlev { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the loro_surmixlev.
|
||||
/// </summary>
|
||||
/// <value>The loro_surmixlev.</value>
|
||||
public string loro_surmixlev { get; set; }
|
||||
|
||||
public string field_order { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the disposition.
|
||||
/// </summary>
|
||||
/// <value>The disposition.</value>
|
||||
public Dictionary<string, string> disposition { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Class MediaFormat
|
||||
/// </summary>
|
||||
public class MediaFormatInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the filename.
|
||||
/// </summary>
|
||||
/// <value>The filename.</value>
|
||||
public string filename { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the nb_streams.
|
||||
/// </summary>
|
||||
/// <value>The nb_streams.</value>
|
||||
public int nb_streams { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the format_name.
|
||||
/// </summary>
|
||||
/// <value>The format_name.</value>
|
||||
public string format_name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the format_long_name.
|
||||
/// </summary>
|
||||
/// <value>The format_long_name.</value>
|
||||
public string format_long_name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the start_time.
|
||||
/// </summary>
|
||||
/// <value>The start_time.</value>
|
||||
public string start_time { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration.
|
||||
/// </summary>
|
||||
/// <value>The duration.</value>
|
||||
public string duration { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the size.
|
||||
/// </summary>
|
||||
/// <value>The size.</value>
|
||||
public string size { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the bit_rate.
|
||||
/// </summary>
|
||||
/// <value>The bit_rate.</value>
|
||||
public string bit_rate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the probe_score.
|
||||
/// </summary>
|
||||
/// <value>The probe_score.</value>
|
||||
public int probe_score { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the tags.
|
||||
/// </summary>
|
||||
/// <value>The tags.</value>
|
||||
public Dictionary<string, string> tags { get; set; }
|
||||
}
|
||||
}
|
||||
1392
MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
Normal file
1392
MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs
Normal file
File diff suppressed because it is too large
Load Diff
33
MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs
Normal file
33
MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("MediaBrowser.MediaEncoding")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("MediaBrowser.MediaEncoding")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2014")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("05f49ab9-2a90-4332-9d41-7817a9cccd90")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
122
MediaBrowser.MediaEncoding/Subtitles/AssParser.cs
Normal file
122
MediaBrowser.MediaEncoding/Subtitles/AssParser.cs
Normal file
@@ -0,0 +1,122 @@
|
||||
using MediaBrowser.Model.Extensions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class AssParser : ISubtitleParser
|
||||
{
|
||||
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
|
||||
|
||||
public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var trackInfo = new SubtitleTrackInfo();
|
||||
List<SubtitleTrackEvent> trackEvents = new List<SubtitleTrackEvent>();
|
||||
var eventIndex = 1;
|
||||
using (var reader = new StreamReader(stream))
|
||||
{
|
||||
string line;
|
||||
while (reader.ReadLine() != "[Events]")
|
||||
{}
|
||||
var headers = ParseFieldHeaders(reader.ReadLine());
|
||||
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if(line.StartsWith("["))
|
||||
break;
|
||||
if(string.IsNullOrEmpty(line))
|
||||
continue;
|
||||
var subEvent = new SubtitleTrackEvent { Id = eventIndex.ToString(_usCulture) };
|
||||
eventIndex++;
|
||||
var sections = line.Substring(10).Split(',');
|
||||
|
||||
subEvent.StartPositionTicks = GetTicks(sections[headers["Start"]]);
|
||||
subEvent.EndPositionTicks = GetTicks(sections[headers["End"]]);
|
||||
|
||||
subEvent.Text = string.Join(",", sections.Skip(headers["Text"]));
|
||||
RemoteNativeFormatting(subEvent);
|
||||
|
||||
subEvent.Text = subEvent.Text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
subEvent.Text = Regex.Replace(subEvent.Text, @"\{(\\[\w]+\(?([\w\d]+,?)+\)?)+\}", string.Empty, RegexOptions.IgnoreCase);
|
||||
|
||||
trackEvents.Add(subEvent);
|
||||
}
|
||||
}
|
||||
trackInfo.TrackEvents = trackEvents.ToArray();
|
||||
return trackInfo;
|
||||
}
|
||||
|
||||
long GetTicks(string time)
|
||||
{
|
||||
TimeSpan span;
|
||||
return TimeSpan.TryParseExact(time, @"h\:mm\:ss\.ff", _usCulture, out span)
|
||||
? span.Ticks: 0;
|
||||
}
|
||||
|
||||
private Dictionary<string,int> ParseFieldHeaders(string line) {
|
||||
var fields = line.Substring(8).Split(',').Select(x=>x.Trim()).ToList();
|
||||
|
||||
var result = new Dictionary<string, int> {
|
||||
{"Start", fields.IndexOf("Start")},
|
||||
{"End", fields.IndexOf("End")},
|
||||
{"Text", fields.IndexOf("Text")}
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Credit: https://github.com/SubtitleEdit/subtitleedit/blob/master/src/Logic/SubtitleFormats/AdvancedSubStationAlpha.cs
|
||||
/// </summary>
|
||||
private void RemoteNativeFormatting(SubtitleTrackEvent p)
|
||||
{
|
||||
int indexOfBegin = p.Text.IndexOf('{');
|
||||
string pre = string.Empty;
|
||||
while (indexOfBegin >= 0 && p.Text.IndexOf('}') > indexOfBegin)
|
||||
{
|
||||
string s = p.Text.Substring(indexOfBegin);
|
||||
if (s.StartsWith("{\\an1}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an2}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an3}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an4}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an5}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an6}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an7}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an8}", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an9}", StringComparison.Ordinal))
|
||||
{
|
||||
pre = s.Substring(0, 6);
|
||||
}
|
||||
else if (s.StartsWith("{\\an1\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an2\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an3\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an4\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an5\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an6\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an7\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an8\\", StringComparison.Ordinal) ||
|
||||
s.StartsWith("{\\an9\\", StringComparison.Ordinal))
|
||||
{
|
||||
pre = s.Substring(0, 5) + "}";
|
||||
}
|
||||
int indexOfEnd = p.Text.IndexOf('}');
|
||||
p.Text = p.Text.Remove(indexOfBegin, (indexOfEnd - indexOfBegin) + 1);
|
||||
|
||||
indexOfBegin = p.Text.IndexOf('{');
|
||||
}
|
||||
p.Text = pre + p.Text;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System.Collections.Generic;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Model.Providers;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public static class ConfigurationExtension
|
||||
{
|
||||
public static SubtitleOptions GetSubtitleConfiguration(this IConfigurationManager manager)
|
||||
{
|
||||
return manager.GetConfiguration<SubtitleOptions>("subtitles");
|
||||
}
|
||||
}
|
||||
|
||||
public class SubtitleConfigurationFactory : IConfigurationFactory
|
||||
{
|
||||
public IEnumerable<ConfigurationStore> GetConfigurations()
|
||||
{
|
||||
return new List<ConfigurationStore>
|
||||
{
|
||||
new ConfigurationStore
|
||||
{
|
||||
Key = "subtitles",
|
||||
ConfigurationType = typeof (SubtitleOptions)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
17
MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs
Normal file
17
MediaBrowser.MediaEncoding/Subtitles/ISubtitleParser.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public interface ISubtitleParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses the specified stream.
|
||||
/// </summary>
|
||||
/// <param name="stream">The stream.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>SubtitleTrackInfo.</returns>
|
||||
SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
20
MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs
Normal file
20
MediaBrowser.MediaEncoding/Subtitles/ISubtitleWriter.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface ISubtitleWriter
|
||||
/// </summary>
|
||||
public interface ISubtitleWriter
|
||||
{
|
||||
/// <summary>
|
||||
/// Writes the specified information.
|
||||
/// </summary>
|
||||
/// <param name="info">The information.</param>
|
||||
/// <param name="stream">The stream.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
28
MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs
Normal file
28
MediaBrowser.MediaEncoding/Subtitles/JsonWriter.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class JsonWriter : ISubtitleWriter
|
||||
{
|
||||
private readonly IJsonSerializer _json;
|
||||
|
||||
public JsonWriter(IJsonSerializer json)
|
||||
{
|
||||
_json = json;
|
||||
}
|
||||
|
||||
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
|
||||
{
|
||||
var json = _json.SerializeToString(info);
|
||||
|
||||
writer.Write(json);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
349
MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
Normal file
349
MediaBrowser.MediaEncoding/Subtitles/OpenSubtitleDownloader.cs
Normal file
@@ -0,0 +1,349 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller.Configuration;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
using MediaBrowser.Controller.Security;
|
||||
using MediaBrowser.Controller.Subtitles;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.Providers;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using OpenSubtitlesHandler;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class OpenSubtitleDownloader : ISubtitleProvider, IDisposable
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
private readonly IHttpClient _httpClient;
|
||||
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
|
||||
|
||||
private readonly IServerConfigurationManager _config;
|
||||
private readonly IEncryptionManager _encryption;
|
||||
|
||||
private readonly IJsonSerializer _json;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
|
||||
public OpenSubtitleDownloader(ILogManager logManager, IHttpClient httpClient, IServerConfigurationManager config, IEncryptionManager encryption, IJsonSerializer json, IFileSystem fileSystem)
|
||||
{
|
||||
_logger = logManager.GetLogger(GetType().Name);
|
||||
_httpClient = httpClient;
|
||||
_config = config;
|
||||
_encryption = encryption;
|
||||
_json = json;
|
||||
_fileSystem = fileSystem;
|
||||
|
||||
_config.NamedConfigurationUpdating += _config_NamedConfigurationUpdating;
|
||||
|
||||
Utilities.HttpClient = httpClient;
|
||||
OpenSubtitles.SetUserAgent("mediabrowser.tv");
|
||||
}
|
||||
|
||||
private const string PasswordHashPrefix = "h:";
|
||||
void _config_NamedConfigurationUpdating(object sender, ConfigurationUpdateEventArgs e)
|
||||
{
|
||||
if (!string.Equals(e.Key, "subtitles", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = (SubtitleOptions)e.NewConfiguration;
|
||||
|
||||
if (options != null &&
|
||||
!string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash) &&
|
||||
!options.OpenSubtitlesPasswordHash.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
options.OpenSubtitlesPasswordHash = EncryptPassword(options.OpenSubtitlesPasswordHash);
|
||||
}
|
||||
}
|
||||
|
||||
private string EncryptPassword(string password)
|
||||
{
|
||||
return PasswordHashPrefix + _encryption.EncryptString(password);
|
||||
}
|
||||
|
||||
private string DecryptPassword(string password)
|
||||
{
|
||||
if (password == null ||
|
||||
!password.StartsWith(PasswordHashPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return _encryption.DecryptString(password.Substring(2));
|
||||
}
|
||||
|
||||
public string Name
|
||||
{
|
||||
get { return "Open Subtitles"; }
|
||||
}
|
||||
|
||||
private SubtitleOptions GetOptions()
|
||||
{
|
||||
return _config.GetSubtitleConfiguration();
|
||||
}
|
||||
|
||||
public IEnumerable<VideoContentType> SupportedMediaTypes
|
||||
{
|
||||
get
|
||||
{
|
||||
var options = GetOptions();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.OpenSubtitlesUsername) ||
|
||||
string.IsNullOrWhiteSpace(options.OpenSubtitlesPasswordHash))
|
||||
{
|
||||
return new VideoContentType[] { };
|
||||
}
|
||||
|
||||
return new[] { VideoContentType.Episode, VideoContentType.Movie };
|
||||
}
|
||||
}
|
||||
|
||||
public Task<SubtitleResponse> GetSubtitles(string id, CancellationToken cancellationToken)
|
||||
{
|
||||
return GetSubtitlesInternal(id, GetOptions(), cancellationToken);
|
||||
}
|
||||
|
||||
private DateTime _lastRateLimitException;
|
||||
private async Task<SubtitleResponse> GetSubtitlesInternal(string id,
|
||||
SubtitleOptions options,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
throw new ArgumentNullException("id");
|
||||
}
|
||||
|
||||
var idParts = id.Split(new[] { '-' }, 3);
|
||||
|
||||
var format = idParts[0];
|
||||
var language = idParts[1];
|
||||
var ossId = idParts[2];
|
||||
|
||||
var downloadsList = new[] { int.Parse(ossId, _usCulture) };
|
||||
|
||||
await Login(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if ((DateTime.UtcNow - _lastRateLimitException).TotalHours < 1)
|
||||
{
|
||||
throw new RateLimitExceededException("OpenSubtitles rate limit reached");
|
||||
}
|
||||
|
||||
var resultDownLoad = await OpenSubtitles.DownloadSubtitlesAsync(downloadsList, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if ((resultDownLoad.Status ?? string.Empty).IndexOf("407", StringComparison.OrdinalIgnoreCase) != -1)
|
||||
{
|
||||
_lastRateLimitException = DateTime.UtcNow;
|
||||
throw new RateLimitExceededException("OpenSubtitles rate limit reached");
|
||||
}
|
||||
|
||||
if (!(resultDownLoad is MethodResponseSubtitleDownload))
|
||||
{
|
||||
throw new Exception("Invalid response type");
|
||||
}
|
||||
|
||||
var results = ((MethodResponseSubtitleDownload)resultDownLoad).Results;
|
||||
|
||||
_lastRateLimitException = DateTime.MinValue;
|
||||
|
||||
if (results.Count == 0)
|
||||
{
|
||||
var msg = string.Format("Subtitle with Id {0} was not found. Name: {1}. Status: {2}. Message: {3}",
|
||||
ossId,
|
||||
resultDownLoad.Name ?? string.Empty,
|
||||
resultDownLoad.Status ?? string.Empty,
|
||||
resultDownLoad.Message ?? string.Empty);
|
||||
|
||||
throw new ResourceNotFoundException(msg);
|
||||
}
|
||||
|
||||
var data = Convert.FromBase64String(results.First().Data);
|
||||
|
||||
return new SubtitleResponse
|
||||
{
|
||||
Format = format,
|
||||
Language = language,
|
||||
|
||||
Stream = new MemoryStream(Utilities.Decompress(new MemoryStream(data)))
|
||||
};
|
||||
}
|
||||
|
||||
private DateTime _lastLogin;
|
||||
private async Task Login(CancellationToken cancellationToken)
|
||||
{
|
||||
if ((DateTime.UtcNow - _lastLogin).TotalSeconds < 60)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var options = GetOptions();
|
||||
|
||||
var user = options.OpenSubtitlesUsername ?? string.Empty;
|
||||
var password = DecryptPassword(options.OpenSubtitlesPasswordHash);
|
||||
|
||||
var loginResponse = await OpenSubtitles.LogInAsync(user, password, "en", cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!(loginResponse is MethodResponseLogIn))
|
||||
{
|
||||
throw new Exception("Authentication to OpenSubtitles failed.");
|
||||
}
|
||||
|
||||
_lastLogin = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<NameIdPair>> GetSupportedLanguages(CancellationToken cancellationToken)
|
||||
{
|
||||
await Login(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var result = OpenSubtitles.GetSubLanguages("en");
|
||||
if (!(result is MethodResponseGetSubLanguages))
|
||||
{
|
||||
_logger.Error("Invalid response type");
|
||||
return new List<NameIdPair>();
|
||||
}
|
||||
|
||||
var results = ((MethodResponseGetSubLanguages)result).Languages;
|
||||
|
||||
return results.Select(i => new NameIdPair
|
||||
{
|
||||
Name = i.LanguageName,
|
||||
Id = i.SubLanguageID
|
||||
});
|
||||
}
|
||||
|
||||
private string NormalizeLanguage(string language)
|
||||
{
|
||||
// Problem with Greek subtitle download #1349
|
||||
if (string.Equals(language, "gre", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
|
||||
return "ell";
|
||||
}
|
||||
|
||||
return language;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<RemoteSubtitleInfo>> Search(SubtitleSearchRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var imdbIdText = request.GetProviderId(MetadataProviders.Imdb);
|
||||
long imdbId = 0;
|
||||
|
||||
switch (request.ContentType)
|
||||
{
|
||||
case VideoContentType.Episode:
|
||||
if (!request.IndexNumber.HasValue || !request.ParentIndexNumber.HasValue || string.IsNullOrEmpty(request.SeriesName))
|
||||
{
|
||||
_logger.Debug("Episode information missing");
|
||||
return new List<RemoteSubtitleInfo>();
|
||||
}
|
||||
break;
|
||||
case VideoContentType.Movie:
|
||||
if (string.IsNullOrEmpty(request.Name))
|
||||
{
|
||||
_logger.Debug("Movie name missing");
|
||||
return new List<RemoteSubtitleInfo>();
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(imdbIdText) || !long.TryParse(imdbIdText.TrimStart('t'), NumberStyles.Any, _usCulture, out imdbId))
|
||||
{
|
||||
_logger.Debug("Imdb id missing");
|
||||
return new List<RemoteSubtitleInfo>();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(request.MediaPath))
|
||||
{
|
||||
_logger.Debug("Path Missing");
|
||||
return new List<RemoteSubtitleInfo>();
|
||||
}
|
||||
|
||||
await Login(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var subLanguageId = NormalizeLanguage(request.Language);
|
||||
string hash;
|
||||
|
||||
using (var fileStream = _fileSystem.OpenRead(request.MediaPath))
|
||||
{
|
||||
hash = Utilities.ComputeHash(fileStream);
|
||||
}
|
||||
var fileInfo = _fileSystem.GetFileInfo(request.MediaPath);
|
||||
var movieByteSize = fileInfo.Length;
|
||||
var searchImdbId = request.ContentType == VideoContentType.Movie ? imdbId.ToString(_usCulture) : "";
|
||||
var subtitleSearchParameters = request.ContentType == VideoContentType.Episode
|
||||
? new List<SubtitleSearchParameters> {
|
||||
new SubtitleSearchParameters(subLanguageId,
|
||||
query: request.SeriesName,
|
||||
season: request.ParentIndexNumber.Value.ToString(_usCulture),
|
||||
episode: request.IndexNumber.Value.ToString(_usCulture))
|
||||
}
|
||||
: new List<SubtitleSearchParameters> {
|
||||
new SubtitleSearchParameters(subLanguageId, imdbid: searchImdbId),
|
||||
new SubtitleSearchParameters(subLanguageId, query: request.Name, imdbid: searchImdbId)
|
||||
};
|
||||
var parms = new List<SubtitleSearchParameters> {
|
||||
new SubtitleSearchParameters( subLanguageId,
|
||||
movieHash: hash,
|
||||
movieByteSize: movieByteSize,
|
||||
imdbid: searchImdbId ),
|
||||
};
|
||||
parms.AddRange(subtitleSearchParameters);
|
||||
var result = await OpenSubtitles.SearchSubtitlesAsync(parms.ToArray(), cancellationToken).ConfigureAwait(false);
|
||||
if (!(result is MethodResponseSubtitleSearch))
|
||||
{
|
||||
_logger.Error("Invalid response type");
|
||||
return new List<RemoteSubtitleInfo>();
|
||||
}
|
||||
|
||||
Predicate<SubtitleSearchResult> mediaFilter =
|
||||
x =>
|
||||
request.ContentType == VideoContentType.Episode
|
||||
? !string.IsNullOrEmpty(x.SeriesSeason) && !string.IsNullOrEmpty(x.SeriesEpisode) &&
|
||||
int.Parse(x.SeriesSeason, _usCulture) == request.ParentIndexNumber &&
|
||||
int.Parse(x.SeriesEpisode, _usCulture) == request.IndexNumber
|
||||
: !string.IsNullOrEmpty(x.IDMovieImdb) && long.Parse(x.IDMovieImdb, _usCulture) == imdbId;
|
||||
|
||||
var results = ((MethodResponseSubtitleSearch)result).Results;
|
||||
|
||||
// Avoid implicitly captured closure
|
||||
var hasCopy = hash;
|
||||
|
||||
return results.Where(x => x.SubBad == "0" && mediaFilter(x) && (!request.IsPerfectMatch || string.Equals(x.MovieHash, hash, StringComparison.OrdinalIgnoreCase)))
|
||||
.OrderBy(x => (string.Equals(x.MovieHash, hash, StringComparison.OrdinalIgnoreCase) ? 0 : 1))
|
||||
.ThenBy(x => Math.Abs(long.Parse(x.MovieByteSize, _usCulture) - movieByteSize))
|
||||
.ThenByDescending(x => int.Parse(x.SubDownloadsCnt, _usCulture))
|
||||
.ThenByDescending(x => double.Parse(x.SubRating, _usCulture))
|
||||
.Select(i => new RemoteSubtitleInfo
|
||||
{
|
||||
Author = i.UserNickName,
|
||||
Comment = i.SubAuthorComment,
|
||||
CommunityRating = float.Parse(i.SubRating, _usCulture),
|
||||
DownloadCount = int.Parse(i.SubDownloadsCnt, _usCulture),
|
||||
Format = i.SubFormat,
|
||||
ProviderName = Name,
|
||||
ThreeLetterISOLanguageName = i.SubLanguageID,
|
||||
|
||||
Id = i.SubFormat + "-" + i.SubLanguageID + "-" + i.IDSubtitleFile,
|
||||
|
||||
Name = i.SubFileName,
|
||||
DateCreated = DateTime.Parse(i.SubAddDate, _usCulture),
|
||||
IsHashMatch = i.MovieHash == hasCopy
|
||||
|
||||
}).Where(i => !string.Equals(i.Format, "sub", StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Format, "idx", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_config.NamedConfigurationUpdating -= _config_NamedConfigurationUpdating;
|
||||
}
|
||||
}
|
||||
}
|
||||
7
MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs
Normal file
7
MediaBrowser.MediaEncoding/Subtitles/ParserValues.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class ParserValues
|
||||
{
|
||||
public const string NewLine = "\r\n";
|
||||
}
|
||||
}
|
||||
92
MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
Normal file
92
MediaBrowser.MediaEncoding/Subtitles/SrtParser.cs
Normal file
@@ -0,0 +1,92 @@
|
||||
using MediaBrowser.Model.Extensions;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class SrtParser : ISubtitleParser
|
||||
{
|
||||
private readonly ILogger _logger;
|
||||
|
||||
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
|
||||
|
||||
public SrtParser(ILogger logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var trackInfo = new SubtitleTrackInfo();
|
||||
List<SubtitleTrackEvent> trackEvents = new List<SubtitleTrackEvent>();
|
||||
using ( var reader = new StreamReader(stream))
|
||||
{
|
||||
string line;
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var subEvent = new SubtitleTrackEvent {Id = line};
|
||||
line = reader.ReadLine();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(line))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var time = Regex.Split(line, @"[\t ]*-->[\t ]*");
|
||||
|
||||
if (time.Length < 2)
|
||||
{
|
||||
// This occurs when subtitle text has an empty line as part of the text.
|
||||
// Need to adjust the break statement below to resolve this.
|
||||
_logger.Warn("Unrecognized line in srt: {0}", line);
|
||||
continue;
|
||||
}
|
||||
subEvent.StartPositionTicks = GetTicks(time[0]);
|
||||
var endTime = time[1];
|
||||
var idx = endTime.IndexOf(" ", StringComparison.Ordinal);
|
||||
if (idx > 0)
|
||||
endTime = endTime.Substring(0, idx);
|
||||
subEvent.EndPositionTicks = GetTicks(endTime);
|
||||
var multiline = new List<string>();
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(line))
|
||||
{
|
||||
break;
|
||||
}
|
||||
multiline.Add(line);
|
||||
}
|
||||
subEvent.Text = string.Join(ParserValues.NewLine, multiline);
|
||||
subEvent.Text = subEvent.Text.Replace(@"\N", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
|
||||
subEvent.Text = Regex.Replace(subEvent.Text, @"\{(?:\\\d?[\w.-]+(?:\([^\)]*\)|&H?[0-9A-Fa-f]+&|))+\}", string.Empty, RegexOptions.IgnoreCase);
|
||||
subEvent.Text = Regex.Replace(subEvent.Text, "<", "<", RegexOptions.IgnoreCase);
|
||||
subEvent.Text = Regex.Replace(subEvent.Text, ">", ">", RegexOptions.IgnoreCase);
|
||||
subEvent.Text = Regex.Replace(subEvent.Text, "<(\\/?(font|b|u|i|s))((\\s+(\\w|\\w[\\w\\-]*\\w)(\\s*=\\s*(?:\\\".*?\\\"|'.*?'|[^'\\\">\\s]+))?)+\\s*|\\s*)(\\/?)>", "<$1$3$7>", RegexOptions.IgnoreCase);
|
||||
trackEvents.Add(subEvent);
|
||||
}
|
||||
}
|
||||
trackInfo.TrackEvents = trackEvents.ToArray();
|
||||
return trackInfo;
|
||||
}
|
||||
|
||||
long GetTicks(string time) {
|
||||
TimeSpan span;
|
||||
return TimeSpan.TryParseExact(time, @"hh\:mm\:ss\.fff", _usCulture, out span)
|
||||
? span.Ticks
|
||||
: (TimeSpan.TryParseExact(time, @"hh\:mm\:ss\,fff", _usCulture, out span)
|
||||
? span.Ticks : 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
39
MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs
Normal file
39
MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class SrtWriter : ISubtitleWriter
|
||||
{
|
||||
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
|
||||
{
|
||||
var index = 1;
|
||||
|
||||
foreach (var trackEvent in info.TrackEvents)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
writer.WriteLine(index.ToString(CultureInfo.InvariantCulture));
|
||||
writer.WriteLine(@"{0:hh\:mm\:ss\,fff} --> {1:hh\:mm\:ss\,fff}", TimeSpan.FromTicks(trackEvent.StartPositionTicks), TimeSpan.FromTicks(trackEvent.EndPositionTicks));
|
||||
|
||||
var text = trackEvent.Text;
|
||||
|
||||
// TODO: Not sure how to handle these
|
||||
text = Regex.Replace(text, @"\\n", " ", RegexOptions.IgnoreCase);
|
||||
|
||||
writer.WriteLine(text);
|
||||
writer.WriteLine(string.Empty);
|
||||
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
397
MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs
Normal file
397
MediaBrowser.MediaEncoding/Subtitles/SsaParser.cs
Normal file
@@ -0,0 +1,397 @@
|
||||
using MediaBrowser.Model.Extensions;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
/// <summary>
|
||||
/// Credit to https://github.com/SubtitleEdit/subtitleedit/blob/a299dc4407a31796364cc6ad83f0d3786194ba22/src/Logic/SubtitleFormats/SubStationAlpha.cs
|
||||
/// </summary>
|
||||
public class SsaParser : ISubtitleParser
|
||||
{
|
||||
public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
var trackInfo = new SubtitleTrackInfo();
|
||||
List<SubtitleTrackEvent> trackEvents = new List<SubtitleTrackEvent>();
|
||||
|
||||
using (var reader = new StreamReader(stream))
|
||||
{
|
||||
bool eventsStarted = false;
|
||||
|
||||
string[] format = "Marked, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text".Split(',');
|
||||
int indexLayer = 0;
|
||||
int indexStart = 1;
|
||||
int indexEnd = 2;
|
||||
int indexStyle = 3;
|
||||
int indexName = 4;
|
||||
int indexEffect = 8;
|
||||
int indexText = 9;
|
||||
int lineNumber = 0;
|
||||
|
||||
var header = new StringBuilder();
|
||||
|
||||
string line;
|
||||
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
lineNumber++;
|
||||
if (!eventsStarted)
|
||||
header.AppendLine(line);
|
||||
|
||||
if (line.Trim().ToLower() == "[events]")
|
||||
{
|
||||
eventsStarted = true;
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(line) && line.Trim().StartsWith(";"))
|
||||
{
|
||||
// skip comment lines
|
||||
}
|
||||
else if (eventsStarted && line.Trim().Length > 0)
|
||||
{
|
||||
string s = line.Trim().ToLower();
|
||||
if (s.StartsWith("format:"))
|
||||
{
|
||||
if (line.Length > 10)
|
||||
{
|
||||
format = line.ToLower().Substring(8).Split(',');
|
||||
for (int i = 0; i < format.Length; i++)
|
||||
{
|
||||
if (format[i].Trim().ToLower() == "layer")
|
||||
indexLayer = i;
|
||||
else if (format[i].Trim().ToLower() == "start")
|
||||
indexStart = i;
|
||||
else if (format[i].Trim().ToLower() == "end")
|
||||
indexEnd = i;
|
||||
else if (format[i].Trim().ToLower() == "text")
|
||||
indexText = i;
|
||||
else if (format[i].Trim().ToLower() == "effect")
|
||||
indexEffect = i;
|
||||
else if (format[i].Trim().ToLower() == "style")
|
||||
indexStyle = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!string.IsNullOrEmpty(s))
|
||||
{
|
||||
string text = string.Empty;
|
||||
string start = string.Empty;
|
||||
string end = string.Empty;
|
||||
string style = string.Empty;
|
||||
string layer = string.Empty;
|
||||
string effect = string.Empty;
|
||||
string name = string.Empty;
|
||||
|
||||
string[] splittedLine;
|
||||
|
||||
if (s.StartsWith("dialogue:"))
|
||||
splittedLine = line.Substring(10).Split(',');
|
||||
else
|
||||
splittedLine = line.Split(',');
|
||||
|
||||
for (int i = 0; i < splittedLine.Length; i++)
|
||||
{
|
||||
if (i == indexStart)
|
||||
start = splittedLine[i].Trim();
|
||||
else if (i == indexEnd)
|
||||
end = splittedLine[i].Trim();
|
||||
else if (i == indexLayer)
|
||||
layer = splittedLine[i];
|
||||
else if (i == indexEffect)
|
||||
effect = splittedLine[i];
|
||||
else if (i == indexText)
|
||||
text = splittedLine[i];
|
||||
else if (i == indexStyle)
|
||||
style = splittedLine[i];
|
||||
else if (i == indexName)
|
||||
name = splittedLine[i];
|
||||
else if (i > indexText)
|
||||
text += "," + splittedLine[i];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var p = new SubtitleTrackEvent();
|
||||
|
||||
p.StartPositionTicks = GetTimeCodeFromString(start);
|
||||
p.EndPositionTicks = GetTimeCodeFromString(end);
|
||||
p.Text = GetFormattedText(text);
|
||||
|
||||
trackEvents.Add(p);
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//if (header.Length > 0)
|
||||
//subtitle.Header = header.ToString();
|
||||
|
||||
//subtitle.Renumber(1);
|
||||
}
|
||||
trackInfo.TrackEvents = trackEvents.ToArray();
|
||||
return trackInfo;
|
||||
}
|
||||
|
||||
private static long GetTimeCodeFromString(string time)
|
||||
{
|
||||
// h:mm:ss.cc
|
||||
string[] timeCode = time.Split(':', '.');
|
||||
return new TimeSpan(0, int.Parse(timeCode[0]),
|
||||
int.Parse(timeCode[1]),
|
||||
int.Parse(timeCode[2]),
|
||||
int.Parse(timeCode[3]) * 10).Ticks;
|
||||
}
|
||||
|
||||
public static string GetFormattedText(string text)
|
||||
{
|
||||
text = text.Replace("\\n", ParserValues.NewLine, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
bool italic = false;
|
||||
|
||||
for (int i = 0; i < 10; i++) // just look ten times...
|
||||
{
|
||||
if (text.Contains(@"{\fn"))
|
||||
{
|
||||
int start = text.IndexOf(@"{\fn");
|
||||
int end = text.IndexOf('}', start);
|
||||
if (end > 0 && !text.Substring(start).StartsWith("{\\fn}"))
|
||||
{
|
||||
string fontName = text.Substring(start + 4, end - (start + 4));
|
||||
string extraTags = string.Empty;
|
||||
CheckAndAddSubTags(ref fontName, ref extraTags, out italic);
|
||||
text = text.Remove(start, end - start + 1);
|
||||
if (italic)
|
||||
text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + "><i>");
|
||||
else
|
||||
text = text.Insert(start, "<font face=\"" + fontName + "\"" + extraTags + ">");
|
||||
|
||||
int indexOfEndTag = text.IndexOf("{\\fn}", start);
|
||||
if (indexOfEndTag > 0)
|
||||
text = text.Remove(indexOfEndTag, "{\\fn}".Length).Insert(indexOfEndTag, "</font>");
|
||||
else
|
||||
text += "</font>";
|
||||
}
|
||||
}
|
||||
|
||||
if (text.Contains(@"{\fs"))
|
||||
{
|
||||
int start = text.IndexOf(@"{\fs");
|
||||
int end = text.IndexOf('}', start);
|
||||
if (end > 0 && !text.Substring(start).StartsWith("{\\fs}"))
|
||||
{
|
||||
string fontSize = text.Substring(start + 4, end - (start + 4));
|
||||
string extraTags = string.Empty;
|
||||
CheckAndAddSubTags(ref fontSize, ref extraTags, out italic);
|
||||
if (IsInteger(fontSize))
|
||||
{
|
||||
text = text.Remove(start, end - start + 1);
|
||||
if (italic)
|
||||
text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + "><i>");
|
||||
else
|
||||
text = text.Insert(start, "<font size=\"" + fontSize + "\"" + extraTags + ">");
|
||||
|
||||
int indexOfEndTag = text.IndexOf("{\\fs}", start);
|
||||
if (indexOfEndTag > 0)
|
||||
text = text.Remove(indexOfEndTag, "{\\fs}".Length).Insert(indexOfEndTag, "</font>");
|
||||
else
|
||||
text += "</font>";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (text.Contains(@"{\c"))
|
||||
{
|
||||
int start = text.IndexOf(@"{\c");
|
||||
int end = text.IndexOf('}', start);
|
||||
if (end > 0 && !text.Substring(start).StartsWith("{\\c}"))
|
||||
{
|
||||
string color = text.Substring(start + 4, end - (start + 4));
|
||||
string extraTags = string.Empty;
|
||||
CheckAndAddSubTags(ref color, ref extraTags, out italic);
|
||||
|
||||
color = color.Replace("&", string.Empty).TrimStart('H');
|
||||
color = color.PadLeft(6, '0');
|
||||
|
||||
// switch to rrggbb from bbggrr
|
||||
color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
|
||||
color = color.ToLower();
|
||||
|
||||
text = text.Remove(start, end - start + 1);
|
||||
if (italic)
|
||||
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
|
||||
else
|
||||
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
|
||||
int indexOfEndTag = text.IndexOf("{\\c}", start);
|
||||
if (indexOfEndTag > 0)
|
||||
text = text.Remove(indexOfEndTag, "{\\c}".Length).Insert(indexOfEndTag, "</font>");
|
||||
else
|
||||
text += "</font>";
|
||||
}
|
||||
}
|
||||
|
||||
if (text.Contains(@"{\1c")) // "1" specifices primary color
|
||||
{
|
||||
int start = text.IndexOf(@"{\1c");
|
||||
int end = text.IndexOf('}', start);
|
||||
if (end > 0 && !text.Substring(start).StartsWith("{\\1c}"))
|
||||
{
|
||||
string color = text.Substring(start + 5, end - (start + 5));
|
||||
string extraTags = string.Empty;
|
||||
CheckAndAddSubTags(ref color, ref extraTags, out italic);
|
||||
|
||||
color = color.Replace("&", string.Empty).TrimStart('H');
|
||||
color = color.PadLeft(6, '0');
|
||||
|
||||
// switch to rrggbb from bbggrr
|
||||
color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
|
||||
color = color.ToLower();
|
||||
|
||||
text = text.Remove(start, end - start + 1);
|
||||
if (italic)
|
||||
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + "><i>");
|
||||
else
|
||||
text = text.Insert(start, "<font color=\"" + color + "\"" + extraTags + ">");
|
||||
text += "</font>";
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
text = text.Replace(@"{\i1}", "<i>");
|
||||
text = text.Replace(@"{\i0}", "</i>");
|
||||
text = text.Replace(@"{\i}", "</i>");
|
||||
if (CountTagInText(text, "<i>") > CountTagInText(text, "</i>"))
|
||||
text += "</i>";
|
||||
|
||||
text = text.Replace(@"{\u1}", "<u>");
|
||||
text = text.Replace(@"{\u0}", "</u>");
|
||||
text = text.Replace(@"{\u}", "</u>");
|
||||
if (CountTagInText(text, "<u>") > CountTagInText(text, "</u>"))
|
||||
text += "</u>";
|
||||
|
||||
text = text.Replace(@"{\b1}", "<b>");
|
||||
text = text.Replace(@"{\b0}", "</b>");
|
||||
text = text.Replace(@"{\b}", "</b>");
|
||||
if (CountTagInText(text, "<b>") > CountTagInText(text, "</b>"))
|
||||
text += "</b>";
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
private static bool IsInteger(string s)
|
||||
{
|
||||
int i;
|
||||
if (int.TryParse(s, out i))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int CountTagInText(string text, string tag)
|
||||
{
|
||||
int count = 0;
|
||||
int index = text.IndexOf(tag);
|
||||
while (index >= 0)
|
||||
{
|
||||
count++;
|
||||
if (index == text.Length)
|
||||
return count;
|
||||
index = text.IndexOf(tag, index + 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
private static void CheckAndAddSubTags(ref string tagName, ref string extraTags, out bool italic)
|
||||
{
|
||||
italic = false;
|
||||
int indexOfSPlit = tagName.IndexOf(@"\");
|
||||
if (indexOfSPlit > 0)
|
||||
{
|
||||
string rest = tagName.Substring(indexOfSPlit).TrimStart('\\');
|
||||
tagName = tagName.Remove(indexOfSPlit);
|
||||
|
||||
for (int i = 0; i < 10; i++)
|
||||
{
|
||||
if (rest.StartsWith("fs") && rest.Length > 2)
|
||||
{
|
||||
indexOfSPlit = rest.IndexOf(@"\");
|
||||
string fontSize = rest;
|
||||
if (indexOfSPlit > 0)
|
||||
{
|
||||
fontSize = rest.Substring(0, indexOfSPlit);
|
||||
rest = rest.Substring(indexOfSPlit).TrimStart('\\');
|
||||
}
|
||||
else
|
||||
{
|
||||
rest = string.Empty;
|
||||
}
|
||||
extraTags += " size=\"" + fontSize.Substring(2) + "\"";
|
||||
}
|
||||
else if (rest.StartsWith("fn") && rest.Length > 2)
|
||||
{
|
||||
indexOfSPlit = rest.IndexOf(@"\");
|
||||
string fontName = rest;
|
||||
if (indexOfSPlit > 0)
|
||||
{
|
||||
fontName = rest.Substring(0, indexOfSPlit);
|
||||
rest = rest.Substring(indexOfSPlit).TrimStart('\\');
|
||||
}
|
||||
else
|
||||
{
|
||||
rest = string.Empty;
|
||||
}
|
||||
extraTags += " face=\"" + fontName.Substring(2) + "\"";
|
||||
}
|
||||
else if (rest.StartsWith("c") && rest.Length > 2)
|
||||
{
|
||||
indexOfSPlit = rest.IndexOf(@"\");
|
||||
string fontColor = rest;
|
||||
if (indexOfSPlit > 0)
|
||||
{
|
||||
fontColor = rest.Substring(0, indexOfSPlit);
|
||||
rest = rest.Substring(indexOfSPlit).TrimStart('\\');
|
||||
}
|
||||
else
|
||||
{
|
||||
rest = string.Empty;
|
||||
}
|
||||
|
||||
string color = fontColor.Substring(2);
|
||||
color = color.Replace("&", string.Empty).TrimStart('H');
|
||||
color = color.PadLeft(6, '0');
|
||||
// switch to rrggbb from bbggrr
|
||||
color = "#" + color.Remove(color.Length - 6) + color.Substring(color.Length - 2, 2) + color.Substring(color.Length - 4, 2) + color.Substring(color.Length - 6, 2);
|
||||
color = color.ToLower();
|
||||
|
||||
extraTags += " color=\"" + color + "\"";
|
||||
}
|
||||
else if (rest.StartsWith("i1") && rest.Length > 1)
|
||||
{
|
||||
indexOfSPlit = rest.IndexOf(@"\");
|
||||
italic = true;
|
||||
if (indexOfSPlit > 0)
|
||||
{
|
||||
rest = rest.Substring(indexOfSPlit).TrimStart('\\');
|
||||
}
|
||||
else
|
||||
{
|
||||
rest = string.Empty;
|
||||
}
|
||||
}
|
||||
else if (rest.Length > 0 && rest.Contains("\\"))
|
||||
{
|
||||
indexOfSPlit = rest.IndexOf(@"\");
|
||||
rest = rest.Substring(indexOfSPlit).TrimStart('\\');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
733
MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
Normal file
733
MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs
Normal file
@@ -0,0 +1,733 @@
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Extensions;
|
||||
using MediaBrowser.Common.Net;
|
||||
using MediaBrowser.Controller.Entities;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.MediaEncoding;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.Logging;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MediaBrowser.Model.IO;
|
||||
using MediaBrowser.Model.Diagnostics;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Text;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class SubtitleEncoder : ISubtitleEncoder
|
||||
{
|
||||
private readonly ILibraryManager _libraryManager;
|
||||
private readonly ILogger _logger;
|
||||
private readonly IApplicationPaths _appPaths;
|
||||
private readonly IFileSystem _fileSystem;
|
||||
private readonly IMediaEncoder _mediaEncoder;
|
||||
private readonly IJsonSerializer _json;
|
||||
private readonly IHttpClient _httpClient;
|
||||
private readonly IMediaSourceManager _mediaSourceManager;
|
||||
private readonly IProcessFactory _processFactory;
|
||||
private readonly ITextEncoding _textEncoding;
|
||||
|
||||
public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json, IHttpClient httpClient, IMediaSourceManager mediaSourceManager, IProcessFactory processFactory, ITextEncoding textEncoding)
|
||||
{
|
||||
_libraryManager = libraryManager;
|
||||
_logger = logger;
|
||||
_appPaths = appPaths;
|
||||
_fileSystem = fileSystem;
|
||||
_mediaEncoder = mediaEncoder;
|
||||
_json = json;
|
||||
_httpClient = httpClient;
|
||||
_processFactory = processFactory;
|
||||
_textEncoding = textEncoding;
|
||||
}
|
||||
|
||||
private string SubtitleCachePath
|
||||
{
|
||||
get
|
||||
{
|
||||
return Path.Combine(_appPaths.DataPath, "subtitles");
|
||||
}
|
||||
}
|
||||
|
||||
private Stream ConvertSubtitles(Stream stream,
|
||||
string inputFormat,
|
||||
string outputFormat,
|
||||
long startTimeTicks,
|
||||
long? endTimeTicks,
|
||||
bool preserveOriginalTimestamps,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
|
||||
try
|
||||
{
|
||||
var reader = GetReader(inputFormat, true);
|
||||
|
||||
var trackInfo = reader.Parse(stream, cancellationToken);
|
||||
|
||||
FilterEvents(trackInfo, startTimeTicks, endTimeTicks, preserveOriginalTimestamps);
|
||||
|
||||
var writer = GetWriter(outputFormat);
|
||||
|
||||
writer.Write(trackInfo, ms, cancellationToken);
|
||||
ms.Position = 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
ms.Dispose();
|
||||
throw;
|
||||
}
|
||||
|
||||
return ms;
|
||||
}
|
||||
|
||||
private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long? endTimeTicks, bool preserveTimestamps)
|
||||
{
|
||||
// Drop subs that are earlier than what we're looking for
|
||||
track.TrackEvents = track.TrackEvents
|
||||
.SkipWhile(i => (i.StartPositionTicks - startPositionTicks) < 0 || (i.EndPositionTicks - startPositionTicks) < 0)
|
||||
.ToArray();
|
||||
|
||||
if (endTimeTicks.HasValue)
|
||||
{
|
||||
var endTime = endTimeTicks.Value;
|
||||
|
||||
track.TrackEvents = track.TrackEvents
|
||||
.TakeWhile(i => i.StartPositionTicks <= endTime)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
if (!preserveTimestamps)
|
||||
{
|
||||
foreach (var trackEvent in track.TrackEvents)
|
||||
{
|
||||
trackEvent.EndPositionTicks -= startPositionTicks;
|
||||
trackEvent.StartPositionTicks -= startPositionTicks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async Task<Stream> ISubtitleEncoder.GetSubtitles(BaseItem item, string mediaSourceId, int subtitleStreamIndex, string outputFormat, long startTimeTicks, long endTimeTicks, bool preserveOriginalTimestamps, CancellationToken cancellationToken)
|
||||
{
|
||||
if (item == null)
|
||||
{
|
||||
throw new ArgumentNullException("item");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(mediaSourceId))
|
||||
{
|
||||
throw new ArgumentNullException("mediaSourceId");
|
||||
}
|
||||
|
||||
// TODO network path substition useful ?
|
||||
var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(item, null, true, true, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var mediaSource = mediaSources
|
||||
.First(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
var subtitleStream = mediaSource.MediaStreams
|
||||
.First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
|
||||
|
||||
var subtitle = await GetSubtitleStream(mediaSource, subtitleStream, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var inputFormat = subtitle.Item2;
|
||||
var writer = TryGetWriter(outputFormat);
|
||||
|
||||
// Return the original if we don't have any way of converting it
|
||||
if (writer == null)
|
||||
{
|
||||
return subtitle.Item1;
|
||||
}
|
||||
|
||||
// Return the original if the same format is being requested
|
||||
// Character encoding was already handled in GetSubtitleStream
|
||||
if (string.Equals(inputFormat, outputFormat, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return subtitle.Item1;
|
||||
}
|
||||
|
||||
using (var stream = subtitle.Item1)
|
||||
{
|
||||
return ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, preserveOriginalTimestamps, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Tuple<Stream, string>> GetSubtitleStream(MediaSourceInfo mediaSource,
|
||||
MediaStream subtitleStream,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var inputFiles = new[] { mediaSource.Path };
|
||||
|
||||
if (mediaSource.VideoType.HasValue)
|
||||
{
|
||||
if (mediaSource.VideoType.Value == VideoType.BluRay || mediaSource.VideoType.Value == VideoType.Dvd)
|
||||
{
|
||||
var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSource.Id));
|
||||
inputFiles = mediaSourceItem.GetPlayableStreamFileNames(_mediaEncoder).ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language, fileInfo.Item2, fileInfo.Item4, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new Tuple<Stream, string>(stream, fileInfo.Item3);
|
||||
}
|
||||
|
||||
private async Task<Stream> GetSubtitleStream(string path, string language, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
|
||||
{
|
||||
if (requiresCharset)
|
||||
{
|
||||
var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true);
|
||||
_logger.Debug("charset {0} detected for {1}", charset ?? "null", path);
|
||||
|
||||
if (!string.IsNullOrEmpty(charset))
|
||||
{
|
||||
using (var inputStream = new MemoryStream(bytes))
|
||||
{
|
||||
using (var reader = new StreamReader(inputStream, _textEncoding.GetEncodingFromCharset(charset)))
|
||||
{
|
||||
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
|
||||
bytes = Encoding.UTF8.GetBytes(text);
|
||||
|
||||
return new MemoryStream(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _fileSystem.OpenRead(path);
|
||||
}
|
||||
|
||||
private async Task<Tuple<string, MediaProtocol, string, bool>> GetReadableFile(string mediaPath,
|
||||
string[] inputFiles,
|
||||
MediaProtocol protocol,
|
||||
MediaStream subtitleStream,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!subtitleStream.IsExternal)
|
||||
{
|
||||
string outputFormat;
|
||||
string outputCodec;
|
||||
|
||||
if (string.Equals(subtitleStream.Codec, "ass", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(subtitleStream.Codec, "ssa", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(subtitleStream.Codec, "srt", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Extract
|
||||
outputCodec = "copy";
|
||||
outputFormat = subtitleStream.Codec;
|
||||
}
|
||||
else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
// Extract
|
||||
outputCodec = "copy";
|
||||
outputFormat = "srt";
|
||||
}
|
||||
else
|
||||
{
|
||||
// Extract
|
||||
outputCodec = "srt";
|
||||
outputFormat = "srt";
|
||||
}
|
||||
|
||||
// Extract
|
||||
var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, "." + outputFormat);
|
||||
|
||||
await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, outputFormat, false);
|
||||
}
|
||||
|
||||
var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
|
||||
.TrimStart('.');
|
||||
|
||||
if (GetReader(currentFormat, false) == null)
|
||||
{
|
||||
// Convert
|
||||
var outputPath = GetSubtitleCachePath(mediaPath, protocol, subtitleStream.Index, ".srt");
|
||||
|
||||
await ConvertTextSubtitleToSrt(subtitleStream.Path, subtitleStream.Language, protocol, outputPath, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return new Tuple<string, MediaProtocol, string, bool>(outputPath, MediaProtocol.File, "srt", true);
|
||||
}
|
||||
|
||||
return new Tuple<string, MediaProtocol, string, bool>(subtitleStream.Path, protocol, currentFormat, true);
|
||||
}
|
||||
|
||||
private ISubtitleParser GetReader(string format, bool throwIfMissing)
|
||||
{
|
||||
if (string.IsNullOrEmpty(format))
|
||||
{
|
||||
throw new ArgumentNullException("format");
|
||||
}
|
||||
|
||||
if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SrtParser(_logger);
|
||||
}
|
||||
if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SsaParser();
|
||||
}
|
||||
if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new AssParser();
|
||||
}
|
||||
|
||||
if (throwIfMissing)
|
||||
{
|
||||
throw new ArgumentException("Unsupported format: " + format);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private ISubtitleWriter TryGetWriter(string format)
|
||||
{
|
||||
if (string.IsNullOrEmpty(format))
|
||||
{
|
||||
throw new ArgumentNullException("format");
|
||||
}
|
||||
|
||||
if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new JsonWriter(_json);
|
||||
}
|
||||
if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new SrtWriter();
|
||||
}
|
||||
if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new VttWriter();
|
||||
}
|
||||
if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return new TtmlWriter();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private ISubtitleWriter GetWriter(string format)
|
||||
{
|
||||
var writer = TryGetWriter(format);
|
||||
|
||||
if (writer != null)
|
||||
{
|
||||
return writer;
|
||||
}
|
||||
|
||||
throw new ArgumentException("Unsupported format: " + format);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The _semaphoreLocks
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<string, SemaphoreSlim> _semaphoreLocks =
|
||||
new ConcurrentDictionary<string, SemaphoreSlim>();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the lock.
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename.</param>
|
||||
/// <returns>System.Object.</returns>
|
||||
private SemaphoreSlim GetLock(string filename)
|
||||
{
|
||||
return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the text subtitle to SRT.
|
||||
/// </summary>
|
||||
/// <param name="inputPath">The input path.</param>
|
||||
/// <param name="inputProtocol">The input protocol.</param>
|
||||
/// <param name="outputPath">The output path.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
private async Task ConvertTextSubtitleToSrt(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
|
||||
{
|
||||
var semaphore = GetLock(outputPath);
|
||||
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
if (!_fileSystem.FileExists(outputPath))
|
||||
{
|
||||
await ConvertTextSubtitleToSrtInternal(inputPath, language, inputProtocol, outputPath, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the text subtitle to SRT internal.
|
||||
/// </summary>
|
||||
/// <param name="inputPath">The input path.</param>
|
||||
/// <param name="inputProtocol">The input protocol.</param>
|
||||
/// <param name="outputPath">The output path.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentNullException">
|
||||
/// inputPath
|
||||
/// or
|
||||
/// outputPath
|
||||
/// </exception>
|
||||
private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string language, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(inputPath))
|
||||
{
|
||||
throw new ArgumentNullException("inputPath");
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(outputPath))
|
||||
{
|
||||
throw new ArgumentNullException("outputPath");
|
||||
}
|
||||
|
||||
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
|
||||
|
||||
var encodingParam = await GetSubtitleFileCharacterSet(inputPath, language, inputProtocol, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!string.IsNullOrEmpty(encodingParam))
|
||||
{
|
||||
encodingParam = " -sub_charenc " + encodingParam;
|
||||
}
|
||||
|
||||
var process = _processFactory.Create(new ProcessOptions
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false,
|
||||
FileName = _mediaEncoder.EncoderPath,
|
||||
Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
|
||||
|
||||
IsHidden = true,
|
||||
ErrorDialog = false
|
||||
});
|
||||
|
||||
_logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error starting ffmpeg", ex);
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
|
||||
|
||||
if (!ranToCompletion)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Killing ffmpeg subtitle conversion process");
|
||||
|
||||
process.Kill();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error killing subtitle conversion process", ex);
|
||||
}
|
||||
}
|
||||
|
||||
var exitCode = ranToCompletion ? process.ExitCode : -1;
|
||||
|
||||
process.Dispose();
|
||||
|
||||
var failed = false;
|
||||
|
||||
if (exitCode == -1)
|
||||
{
|
||||
failed = true;
|
||||
|
||||
if (_fileSystem.FileExists(outputPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Deleting converted subtitle due to failure: ", outputPath);
|
||||
_fileSystem.DeleteFile(outputPath);
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
_logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (!_fileSystem.FileExists(outputPath))
|
||||
{
|
||||
failed = true;
|
||||
}
|
||||
|
||||
if (failed)
|
||||
{
|
||||
var msg = string.Format("ffmpeg subtitle conversion failed for {0}", inputPath);
|
||||
|
||||
_logger.Error(msg);
|
||||
|
||||
throw new Exception(msg);
|
||||
}
|
||||
await SetAssFont(outputPath).ConfigureAwait(false);
|
||||
|
||||
_logger.Info("ffmpeg subtitle conversion succeeded for {0}", inputPath);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the text subtitle.
|
||||
/// </summary>
|
||||
/// <param name="inputFiles">The input files.</param>
|
||||
/// <param name="protocol">The protocol.</param>
|
||||
/// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
|
||||
/// <param name="outputCodec">The output codec.</param>
|
||||
/// <param name="outputPath">The output path.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>Task.</returns>
|
||||
/// <exception cref="System.ArgumentException">Must use inputPath list overload</exception>
|
||||
private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
|
||||
string outputCodec, string outputPath, CancellationToken cancellationToken)
|
||||
{
|
||||
var semaphore = GetLock(outputPath);
|
||||
|
||||
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
if (!_fileSystem.FileExists(outputPath))
|
||||
{
|
||||
await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex, outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
|
||||
string outputCodec, string outputPath, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrEmpty(inputPath))
|
||||
{
|
||||
throw new ArgumentNullException("inputPath");
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(outputPath))
|
||||
{
|
||||
throw new ArgumentNullException("outputPath");
|
||||
}
|
||||
|
||||
_fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(outputPath));
|
||||
|
||||
var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
|
||||
subtitleStreamIndex, outputCodec, outputPath);
|
||||
|
||||
var process = _processFactory.Create(new ProcessOptions
|
||||
{
|
||||
CreateNoWindow = true,
|
||||
UseShellExecute = false,
|
||||
|
||||
FileName = _mediaEncoder.EncoderPath,
|
||||
Arguments = processArgs,
|
||||
IsHidden = true,
|
||||
ErrorDialog = false
|
||||
});
|
||||
|
||||
_logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
|
||||
|
||||
try
|
||||
{
|
||||
process.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error starting ffmpeg", ex);
|
||||
|
||||
throw;
|
||||
}
|
||||
|
||||
var ranToCompletion = await process.WaitForExitAsync(300000).ConfigureAwait(false);
|
||||
|
||||
if (!ranToCompletion)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Killing ffmpeg subtitle extraction process");
|
||||
|
||||
process.Kill();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.ErrorException("Error killing subtitle extraction process", ex);
|
||||
}
|
||||
}
|
||||
|
||||
var exitCode = ranToCompletion ? process.ExitCode : -1;
|
||||
|
||||
process.Dispose();
|
||||
|
||||
var failed = false;
|
||||
|
||||
if (exitCode == -1)
|
||||
{
|
||||
failed = true;
|
||||
|
||||
try
|
||||
{
|
||||
_logger.Info("Deleting extracted subtitle due to failure: {0}", outputPath);
|
||||
_fileSystem.DeleteFile(outputPath);
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
|
||||
}
|
||||
catch (IOException ex)
|
||||
{
|
||||
_logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
|
||||
}
|
||||
}
|
||||
else if (!_fileSystem.FileExists(outputPath))
|
||||
{
|
||||
failed = true;
|
||||
}
|
||||
|
||||
if (failed)
|
||||
{
|
||||
var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
|
||||
|
||||
_logger.Error(msg);
|
||||
|
||||
throw new Exception(msg);
|
||||
}
|
||||
else
|
||||
{
|
||||
var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath);
|
||||
|
||||
_logger.Info(msg);
|
||||
}
|
||||
|
||||
if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await SetAssFont(outputPath).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the ass font.
|
||||
/// </summary>
|
||||
/// <param name="file">The file.</param>
|
||||
/// <returns>Task.</returns>
|
||||
private async Task SetAssFont(string file)
|
||||
{
|
||||
_logger.Info("Setting ass font within {0}", file);
|
||||
|
||||
string text;
|
||||
Encoding encoding;
|
||||
|
||||
using (var fileStream = _fileSystem.OpenRead(file))
|
||||
{
|
||||
using (var reader = new StreamReader(fileStream, true))
|
||||
{
|
||||
encoding = reader.CurrentEncoding;
|
||||
|
||||
text = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
var newText = text.Replace(",Arial,", ",Arial Unicode MS,");
|
||||
|
||||
if (!string.Equals(text, newText))
|
||||
{
|
||||
using (var fileStream = _fileSystem.GetFileStream(file, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
|
||||
{
|
||||
using (var writer = new StreamWriter(fileStream, encoding))
|
||||
{
|
||||
writer.Write(newText);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string GetSubtitleCachePath(string mediaPath, MediaProtocol protocol, int subtitleStreamIndex, string outputSubtitleExtension)
|
||||
{
|
||||
if (protocol == MediaProtocol.File)
|
||||
{
|
||||
var ticksParam = string.Empty;
|
||||
|
||||
var date = _fileSystem.GetLastWriteTimeUtc(mediaPath);
|
||||
|
||||
var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture) + "_" + date.Ticks.ToString(CultureInfo.InvariantCulture) + ticksParam).GetMD5() + outputSubtitleExtension;
|
||||
|
||||
var prefix = filename.Substring(0, 1);
|
||||
|
||||
return Path.Combine(SubtitleCachePath, prefix, filename);
|
||||
}
|
||||
else
|
||||
{
|
||||
var filename = (mediaPath + "_" + subtitleStreamIndex.ToString(CultureInfo.InvariantCulture)).GetMD5() + outputSubtitleExtension;
|
||||
|
||||
var prefix = filename.Substring(0, 1);
|
||||
|
||||
return Path.Combine(SubtitleCachePath, prefix, filename);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> GetSubtitleFileCharacterSet(string path, string language, MediaProtocol protocol, CancellationToken cancellationToken)
|
||||
{
|
||||
var bytes = await GetBytes(path, protocol, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var charset = _textEncoding.GetDetectedEncodingName(bytes, bytes.Length, language, true);
|
||||
|
||||
_logger.Debug("charset {0} detected for {1}", charset ?? "null", path);
|
||||
|
||||
return charset;
|
||||
}
|
||||
|
||||
private async Task<byte[]> GetBytes(string path, MediaProtocol protocol, CancellationToken cancellationToken)
|
||||
{
|
||||
if (protocol == MediaProtocol.Http)
|
||||
{
|
||||
HttpRequestOptions opts = new HttpRequestOptions();
|
||||
opts.Url = path;
|
||||
opts.CancellationToken = cancellationToken;
|
||||
using (var file = await _httpClient.Get(opts).ConfigureAwait(false))
|
||||
{
|
||||
using (var memoryStream = new MemoryStream())
|
||||
{
|
||||
await file.CopyToAsync(memoryStream).ConfigureAwait(false);
|
||||
memoryStream.Position = 0;
|
||||
|
||||
return memoryStream.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (protocol == MediaProtocol.File)
|
||||
{
|
||||
return _fileSystem.ReadAllBytes(path);
|
||||
}
|
||||
|
||||
throw new ArgumentOutOfRangeException("protocol");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
60
MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs
Normal file
60
MediaBrowser.MediaEncoding/Subtitles/TtmlWriter.cs
Normal file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class TtmlWriter : ISubtitleWriter
|
||||
{
|
||||
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
// Example: https://github.com/zmalltalker/ttml2vtt/blob/master/data/sample.xml
|
||||
// Parser example: https://github.com/mozilla/popcorn-js/blob/master/parsers/parserTTML/popcorn.parserTTML.js
|
||||
|
||||
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
|
||||
{
|
||||
writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
|
||||
writer.WriteLine("<tt xmlns=\"http://www.w3.org/ns/ttml\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\" lang=\"no\">");
|
||||
|
||||
writer.WriteLine("<head>");
|
||||
writer.WriteLine("<styling>");
|
||||
writer.WriteLine("<style id=\"italic\" tts:fontStyle=\"italic\" />");
|
||||
writer.WriteLine("<style id=\"left\" tts:textAlign=\"left\" />");
|
||||
writer.WriteLine("<style id=\"center\" tts:textAlign=\"center\" />");
|
||||
writer.WriteLine("<style id=\"right\" tts:textAlign=\"right\" />");
|
||||
writer.WriteLine("</styling>");
|
||||
writer.WriteLine("</head>");
|
||||
|
||||
writer.WriteLine("<body>");
|
||||
writer.WriteLine("<div>");
|
||||
|
||||
foreach (var trackEvent in info.TrackEvents)
|
||||
{
|
||||
var text = trackEvent.Text;
|
||||
|
||||
text = Regex.Replace(text, @"\\n", "<br/>", RegexOptions.IgnoreCase);
|
||||
|
||||
writer.WriteLine("<p begin=\"{0}\" dur=\"{1}\">{2}</p>",
|
||||
trackEvent.StartPositionTicks,
|
||||
(trackEvent.EndPositionTicks - trackEvent.StartPositionTicks),
|
||||
text);
|
||||
}
|
||||
|
||||
writer.WriteLine("</div>");
|
||||
writer.WriteLine("</body>");
|
||||
|
||||
writer.WriteLine("</tt>");
|
||||
}
|
||||
}
|
||||
|
||||
private string FormatTime(long ticks)
|
||||
{
|
||||
var time = TimeSpan.FromTicks(ticks);
|
||||
|
||||
return string.Format(@"{0:hh\:mm\:ss\,fff}", time);
|
||||
}
|
||||
}
|
||||
}
|
||||
44
MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs
Normal file
44
MediaBrowser.MediaEncoding/Subtitles/VttWriter.cs
Normal file
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
|
||||
namespace MediaBrowser.MediaEncoding.Subtitles
|
||||
{
|
||||
public class VttWriter : ISubtitleWriter
|
||||
{
|
||||
public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
|
||||
{
|
||||
using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
|
||||
{
|
||||
writer.WriteLine("WEBVTT");
|
||||
writer.WriteLine(string.Empty);
|
||||
foreach (var trackEvent in info.TrackEvents)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
TimeSpan startTime = TimeSpan.FromTicks(trackEvent.StartPositionTicks);
|
||||
TimeSpan endTime = TimeSpan.FromTicks(trackEvent.EndPositionTicks);
|
||||
|
||||
// make sure the start and end times are different and seqential
|
||||
if (endTime.TotalMilliseconds <= startTime.TotalMilliseconds)
|
||||
{
|
||||
endTime = startTime.Add(TimeSpan.FromMilliseconds(1));
|
||||
}
|
||||
|
||||
writer.WriteLine(@"{0:hh\:mm\:ss\.fff} --> {1:hh\:mm\:ss\.fff}", startTime, endTime);
|
||||
|
||||
var text = trackEvent.Text;
|
||||
|
||||
// TODO: Not sure how to handle these
|
||||
text = Regex.Replace(text, @"\\n", " ", RegexOptions.IgnoreCase);
|
||||
|
||||
writer.WriteLine(text);
|
||||
writer.WriteLine(string.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
3
MediaBrowser.MediaEncoding/packages.config
Normal file
3
MediaBrowser.MediaEncoding/packages.config
Normal file
@@ -0,0 +1,3 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
</packages>
|
||||
Reference in New Issue
Block a user