| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856 | 
							- using MediaBrowser.Common.Configuration;
 
- using MediaBrowser.Common.Extensions;
 
- using MediaBrowser.Common.IO;
 
- 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 UniversalDetector;
 
- 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;
 
-         public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json, IHttpClient httpClient, IMediaSourceManager mediaSourceManager)
 
-         {
 
-             _libraryManager = libraryManager;
 
-             _logger = logger;
 
-             _appPaths = appPaths;
 
-             _fileSystem = fileSystem;
 
-             _mediaEncoder = mediaEncoder;
 
-             _json = json;
 
-             _httpClient = httpClient;
 
-             _mediaSourceManager = mediaSourceManager;
 
-         }
 
-         private string SubtitleCachePath
 
-         {
 
-             get
 
-             {
 
-                 return Path.Combine(_appPaths.CachePath, "subtitles");
 
-             }
 
-         }
 
-         public async Task<Stream> ConvertSubtitles(Stream stream,
 
-             string inputFormat,
 
-             string outputFormat,
 
-             long startTimeTicks,
 
-             long? endTimeTicks,
 
-             CancellationToken cancellationToken)
 
-         {
 
-             var ms = new MemoryStream();
 
-             try
 
-             {
 
-                 var trackInfo = await GetTrackInfo(stream, inputFormat, cancellationToken).ConfigureAwait(false);
 
-                 FilterEvents(trackInfo, startTimeTicks, endTimeTicks, false);
 
-                 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)
 
-                 .ToList();
 
-             if (endTimeTicks.HasValue)
 
-             {
 
-                 var endTime = endTimeTicks.Value;
 
-                 track.TrackEvents = track.TrackEvents
 
-                     .TakeWhile(i => i.StartPositionTicks <= endTime)
 
-                     .ToList();
 
-             }
 
-             if (!preserveTimestamps)
 
-             {
 
-                 foreach (var trackEvent in track.TrackEvents)
 
-                 {
 
-                     trackEvent.EndPositionTicks -= startPositionTicks;
 
-                     trackEvent.StartPositionTicks -= startPositionTicks;
 
-                 }
 
-             }
 
-         }
 
-         public async Task<Stream> GetSubtitles(string itemId,
 
-             string mediaSourceId,
 
-             int subtitleStreamIndex,
 
-             string outputFormat,
 
-             long startTimeTicks,
 
-             long? endTimeTicks,
 
-             CancellationToken cancellationToken)
 
-         {
 
-             var subtitle = await GetSubtitleStream(itemId, mediaSourceId, subtitleStreamIndex, cancellationToken)
 
-                         .ConfigureAwait(false);
 
-             using (var stream = subtitle.Item1)
 
-             {
 
-                 var inputFormat = subtitle.Item2;
 
-                 return await ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, cancellationToken).ConfigureAwait(false);
 
-             }
 
-         }
 
-         private async Task<Tuple<Stream, string>> GetSubtitleStream(string itemId,
 
-             string mediaSourceId,
 
-             int subtitleStreamIndex,
 
-             CancellationToken cancellationToken)
 
-         {
 
-             var mediaSources = await _mediaSourceManager.GetPlayackMediaSources(itemId, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false);
 
-             var mediaSource = mediaSources
 
-                 .First(i => string.Equals(i.Id, mediaSourceId));
 
-             var subtitleStream = mediaSource.MediaStreams
 
-                 .First(i => i.Type == MediaStreamType.Subtitle && i.Index == subtitleStreamIndex);
 
-             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(mediaSourceId));
 
-                     inputFiles = mediaSourceItem.GetPlayableStreamFiles().ToArray();
 
-                 }
 
-             }
 
-             var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
 
-             var stream = await GetSubtitleStream(fileInfo.Item1, fileInfo.Item2, fileInfo.Item4, cancellationToken).ConfigureAwait(false);
 
-             return new Tuple<Stream, string>(stream, fileInfo.Item3);
 
-         }
 
-         private async Task<Stream> GetSubtitleStream(string path, MediaProtocol protocol, bool requiresCharset, CancellationToken cancellationToken)
 
-         {
 
-             if (requiresCharset)
 
-             {
 
-                 var charset = await GetSubtitleFileCharacterSet(path, protocol, cancellationToken).ConfigureAwait(false);
 
-                 if (!string.IsNullOrEmpty(charset))
 
-                 {
 
-                     using (var fs = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
 
-                     {
 
-                         using (var reader = new StreamReader(fs, GetEncoding(charset)))
 
-                         {
 
-                             var text = await reader.ReadToEndAsync().ConfigureAwait(false);
 
-                             var bytes = Encoding.UTF8.GetBytes(text);
 
-                             return new MemoryStream(bytes);
 
-                         }
 
-                     }
 
-                 }
 
-             }
 
-             return File.OpenRead(path);
 
-         }
 
-         private Encoding GetEncoding(string charset)
 
-         {
 
-             if (string.IsNullOrWhiteSpace(charset))
 
-             {
 
-                 throw new ArgumentNullException("charset");
 
-             }
 
-             try
 
-             {
 
-                 return Encoding.GetEncoding(charset);
 
-             }
 
-             catch (ArgumentException)
 
-             {
 
-                 return Encoding.GetEncoding(charset.Replace("-", string.Empty));
 
-             }
 
-         }
 
-         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))
 
-                 {
 
-                     // Extract    
 
-                     outputCodec = "copy";
 
-                     outputFormat = "ass";
 
-                 }
 
-                 else if (string.Equals(subtitleStream.Codec, "subrip", StringComparison.OrdinalIgnoreCase) ||
 
-                          string.Equals(subtitleStream.Codec, "srt", 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, 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 async Task<SubtitleTrackInfo> GetTrackInfo(Stream stream,
 
-             string inputFormat,
 
-             CancellationToken cancellationToken)
 
-         {
 
-             var reader = GetReader(inputFormat, true);
 
-             return reader.Parse(stream, cancellationToken);
 
-         }
 
-         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 GetWriter(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();
 
-             }
 
-             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, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
 
-         {
 
-             var semaphore = GetLock(outputPath);
 
-             await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
 
-             try
 
-             {
 
-                 if (!File.Exists(outputPath))
 
-                 {
 
-                     await ConvertTextSubtitleToSrtInternal(inputPath, 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>
 
-         /// <exception cref="System.ApplicationException"></exception>
 
-         private async Task ConvertTextSubtitleToSrtInternal(string inputPath, MediaProtocol inputProtocol, string outputPath, CancellationToken cancellationToken)
 
-         {
 
-             if (string.IsNullOrEmpty(inputPath))
 
-             {
 
-                 throw new ArgumentNullException("inputPath");
 
-             }
 
-             if (string.IsNullOrEmpty(outputPath))
 
-             {
 
-                 throw new ArgumentNullException("outputPath");
 
-             }
 
-             Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
 
-             var encodingParam = await GetSubtitleFileCharacterSet(inputPath, inputProtocol, cancellationToken).ConfigureAwait(false);
 
-             if (!string.IsNullOrEmpty(encodingParam))
 
-             {
 
-                 encodingParam = " -sub_charenc " + encodingParam;
 
-             }
 
-             var process = new Process
 
-             {
 
-                 StartInfo = new ProcessStartInfo
 
-                 {
 
-                     RedirectStandardOutput = false,
 
-                     RedirectStandardError = true,
 
-                     RedirectStandardInput = true,
 
-                     CreateNoWindow = true,
 
-                     UseShellExecute = false,
 
-                     FileName = _mediaEncoder.EncoderPath,
 
-                     Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
 
-                     WindowStyle = ProcessWindowStyle.Hidden,
 
-                     ErrorDialog = false
 
-                 }
 
-             };
 
-             _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
 
-             var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt");
 
-             Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
 
-             var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
 
-                 true);
 
-             try
 
-             {
 
-                 process.Start();
 
-             }
 
-             catch (Exception ex)
 
-             {
 
-                 logFileStream.Dispose();
 
-                 _logger.ErrorException("Error starting ffmpeg", ex);
 
-                 throw;
 
-             }
 
-             var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream);
 
-             var ranToCompletion = process.WaitForExit(60000);
 
-             if (!ranToCompletion)
 
-             {
 
-                 try
 
-                 {
 
-                     _logger.Info("Killing ffmpeg subtitle conversion process");
 
-                     process.StandardInput.WriteLine("q");
 
-                     process.WaitForExit(1000);
 
-                     await logTask.ConfigureAwait(false);
 
-                 }
 
-                 catch (Exception ex)
 
-                 {
 
-                     _logger.ErrorException("Error killing subtitle conversion process", ex);
 
-                 }
 
-                 finally
 
-                 {
 
-                     logFileStream.Dispose();
 
-                 }
 
-             }
 
-             var exitCode = ranToCompletion ? process.ExitCode : -1;
 
-             process.Dispose();
 
-             var failed = false;
 
-             if (exitCode == -1)
 
-             {
 
-                 failed = true;
 
-                 if (File.Exists(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 (!File.Exists(outputPath))
 
-             {
 
-                 failed = true;
 
-             }
 
-             if (failed)
 
-             {
 
-                 var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath);
 
-                 _logger.Error(msg);
 
-                 throw new ApplicationException(msg);
 
-             }
 
-             await SetAssFont(outputPath).ConfigureAwait(false);
 
-         }
 
-         /// <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 (!File.Exists(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");
 
-             }
 
-             Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
 
-             var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
 
-                 subtitleStreamIndex, outputCodec, outputPath);
 
-             var process = new Process
 
-             {
 
-                 StartInfo = new ProcessStartInfo
 
-                 {
 
-                     CreateNoWindow = true,
 
-                     UseShellExecute = false,
 
-                     RedirectStandardOutput = false,
 
-                     RedirectStandardError = true,
 
-                     RedirectStandardInput = true,
 
-                     FileName = _mediaEncoder.EncoderPath,
 
-                     Arguments = processArgs,
 
-                     WindowStyle = ProcessWindowStyle.Hidden,
 
-                     ErrorDialog = false
 
-                 }
 
-             };
 
-             _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
 
-             var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt");
 
-             Directory.CreateDirectory(Path.GetDirectoryName(logFilePath));
 
-             var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read,
 
-                 true);
 
-             try
 
-             {
 
-                 process.Start();
 
-             }
 
-             catch (Exception ex)
 
-             {
 
-                 logFileStream.Dispose();
 
-                 _logger.ErrorException("Error starting ffmpeg", ex);
 
-                 throw;
 
-             }
 
-             process.StandardError.BaseStream.CopyToAsync(logFileStream);
 
-             var ranToCompletion = process.WaitForExit(60000);
 
-             if (!ranToCompletion)
 
-             {
 
-                 try
 
-                 {
 
-                     _logger.Info("Killing ffmpeg subtitle extraction process");
 
-                     process.StandardInput.WriteLine("q");
 
-                     process.WaitForExit(1000);
 
-                 }
 
-                 catch (Exception ex)
 
-                 {
 
-                     _logger.ErrorException("Error killing subtitle extraction process", ex);
 
-                 }
 
-                 finally
 
-                 {
 
-                     logFileStream.Dispose();
 
-                 }
 
-             }
 
-             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 (DirectoryNotFoundException)
 
-                 {
 
-                 }
 
-                 catch (IOException ex)
 
-                 {
 
-                     _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
 
-                 }
 
-             }
 
-             else if (!File.Exists(outputPath))
 
-             {
 
-                 failed = true;
 
-             }
 
-             if (failed)
 
-             {
 
-                 var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath);
 
-                 _logger.Error(msg);
 
-                 throw new ApplicationException(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 reader = new StreamReader(file, 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 writer = new StreamWriter(file, false, 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, MediaProtocol protocol, CancellationToken cancellationToken)
 
-         {
 
-             if (protocol == MediaProtocol.File)
 
-             {
 
-                 if (GetFileEncoding(path).Equals(Encoding.UTF8))
 
-                 {
 
-                     return string.Empty;
 
-                 }
 
-             }
 
-             var charset = await DetectCharset(path, protocol, cancellationToken).ConfigureAwait(false);
 
-             if (!string.IsNullOrWhiteSpace(charset))
 
-             {
 
-                 if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
 
-                 {
 
-                     return null;
 
-                 }
 
-                 return charset;
 
-             }
 
-             return null;
 
-         }
 
-         public string GetSubtitleFileCharacterSetFromLanguage(string language)
 
-         {
 
-             switch (language.ToLower())
 
-             {
 
-                 case "pol":
 
-                 case "cze":
 
-                 case "ces":
 
-                 case "slo":
 
-                 case "slk":
 
-                 case "hun":
 
-                 case "slv":
 
-                 case "srp":
 
-                 case "hrv":
 
-                 case "rum":
 
-                 case "ron":
 
-                 case "rup":
 
-                 case "alb":
 
-                 case "sqi":
 
-                     return "windows-1250";
 
-                 case "ara":
 
-                     return "windows-1256";
 
-                 case "heb":
 
-                     return "windows-1255";
 
-                 case "grc":
 
-                 case "gre":
 
-                     return "windows-1253";
 
-                 case "crh":
 
-                 case "ota":
 
-                 case "tur":
 
-                     return "windows-1254";
 
-                 case "rus":
 
-                     return "windows-1251";
 
-                 case "vie":
 
-                     return "windows-1258";
 
-                 case "kor":
 
-                     return "cp949";
 
-                 default:
 
-                     return "windows-1252";
 
-             }
 
-         }
 
-         private async Task<string> DetectCharset(string path, MediaProtocol protocol, CancellationToken cancellationToken)
 
-         {
 
-             try
 
-             {
 
-                 using (var file = await GetStream(path, protocol, cancellationToken).ConfigureAwait(false))
 
-                 {
 
-                     var detector = new CharsetDetector();
 
-                     detector.Feed(file);
 
-                     detector.DataEnd();
 
-                     var charset = detector.Charset;
 
-                     if (!string.IsNullOrWhiteSpace(charset))
 
-                     {
 
-                         _logger.Info("UniversalDetector detected charset {0} for {1}", charset, path);
 
-                     }
 
-                     return charset;
 
-                 }
 
-             }
 
-             catch (IOException ex)
 
-             {
 
-                 _logger.ErrorException("Error attempting to determine subtitle charset from {0}", ex, path);
 
-             }
 
-             return null;
 
-         }
 
-         private Encoding GetFileEncoding(string srcFile)
 
-         {
 
-             // *** Detect byte order mark if any - otherwise assume default
 
-             var buffer = new byte[5];
 
-             using (var file = _fileSystem.GetFileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
 
-             {
 
-                 file.Read(buffer, 0, 5);
 
-             }
 
-             if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
 
-                 return Encoding.UTF8;
 
-             if (buffer[0] == 0xfe && buffer[1] == 0xff)
 
-                 return Encoding.Unicode;
 
-             if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
 
-                 return Encoding.UTF32;
 
-             if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
 
-                 return Encoding.UTF7;
 
-             // It's ok - anything aside from utf is ok since that's what we're looking for
 
-             return Encoding.Default;
 
-         }
 
-         private async Task<Stream> GetStream(string path, MediaProtocol protocol, CancellationToken cancellationToken)
 
-         {
 
-             if (protocol == MediaProtocol.Http)
 
-             {
 
-                 return await _httpClient.Get(path, cancellationToken).ConfigureAwait(false);
 
-             }
 
-             if (protocol == MediaProtocol.File)
 
-             {
 
-                 return _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
 
-             }
 
-             throw new ArgumentOutOfRangeException("protocol");
 
-         }
 
-     }
 
- }
 
 
  |