2014-06-11 07:42:03 -07:00
|
|
|
|
using MediaBrowser.Common.Configuration;
|
|
|
|
|
using MediaBrowser.Common.Extensions;
|
|
|
|
|
using MediaBrowser.Common.IO;
|
|
|
|
|
using MediaBrowser.Controller.Entities;
|
|
|
|
|
using MediaBrowser.Controller.Library;
|
|
|
|
|
using MediaBrowser.Controller.MediaEncoding;
|
|
|
|
|
using MediaBrowser.Model.Entities;
|
|
|
|
|
using MediaBrowser.Model.Logging;
|
|
|
|
|
using MediaBrowser.Model.MediaInfo;
|
2014-08-22 08:47:44 -07:00
|
|
|
|
using MediaBrowser.Model.Serialization;
|
2014-06-11 07:42:03 -07:00
|
|
|
|
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;
|
2015-01-10 12:42:14 -07:00
|
|
|
|
using UniversalDetector;
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
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;
|
2014-08-22 08:47:44 -07:00
|
|
|
|
private readonly IJsonSerializer _json;
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
2014-08-22 08:47:44 -07:00
|
|
|
|
public SubtitleEncoder(ILibraryManager libraryManager, ILogger logger, IApplicationPaths appPaths, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IJsonSerializer json)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
|
|
|
|
_libraryManager = libraryManager;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
_appPaths = appPaths;
|
|
|
|
|
_fileSystem = fileSystem;
|
|
|
|
|
_mediaEncoder = mediaEncoder;
|
2014-08-22 08:47:44 -07:00
|
|
|
|
_json = json;
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private string SubtitleCachePath
|
|
|
|
|
{
|
|
|
|
|
get
|
|
|
|
|
{
|
|
|
|
|
return Path.Combine(_appPaths.CachePath, "subtitles");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<Stream> ConvertSubtitles(Stream stream,
|
|
|
|
|
string inputFormat,
|
|
|
|
|
string outputFormat,
|
2014-06-11 12:31:33 -07:00
|
|
|
|
long startTimeTicks,
|
2014-08-05 16:59:24 -07:00
|
|
|
|
long? endTimeTicks,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
var ms = new MemoryStream();
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2014-11-04 05:41:12 -07:00
|
|
|
|
var trackInfo = await GetTrackInfo(stream, inputFormat, cancellationToken).ConfigureAwait(false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
2014-11-04 05:41:12 -07:00
|
|
|
|
FilterEvents(trackInfo, startTimeTicks, endTimeTicks, false);
|
2014-06-11 12:31:33 -07:00
|
|
|
|
|
2014-11-04 05:41:12 -07:00
|
|
|
|
var writer = GetWriter(outputFormat);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
2014-11-04 05:41:12 -07:00
|
|
|
|
writer.Write(trackInfo, ms, cancellationToken);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
ms.Position = 0;
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
ms.Dispose();
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ms;
|
|
|
|
|
}
|
|
|
|
|
|
2014-08-05 16:59:24 -07:00
|
|
|
|
private void FilterEvents(SubtitleTrackInfo track, long startPositionTicks, long? endTimeTicks, bool preserveTimestamps)
|
2014-06-11 12:31:33 -07:00
|
|
|
|
{
|
2014-08-05 16:59:24 -07:00
|
|
|
|
// 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();
|
2014-06-11 12:31:33 -07:00
|
|
|
|
|
2014-08-05 16:59:24 -07:00
|
|
|
|
if (endTimeTicks.HasValue)
|
2014-06-11 12:31:33 -07:00
|
|
|
|
{
|
2014-08-05 16:59:24 -07:00
|
|
|
|
var endTime = endTimeTicks.Value;
|
|
|
|
|
|
|
|
|
|
track.TrackEvents = track.TrackEvents
|
|
|
|
|
.TakeWhile(i => i.StartPositionTicks <= endTime)
|
|
|
|
|
.ToList();
|
2014-06-11 12:31:33 -07:00
|
|
|
|
}
|
|
|
|
|
|
2014-08-05 16:59:24 -07:00
|
|
|
|
if (!preserveTimestamps)
|
|
|
|
|
{
|
|
|
|
|
foreach (var trackEvent in track.TrackEvents)
|
|
|
|
|
{
|
|
|
|
|
trackEvent.EndPositionTicks -= startPositionTicks;
|
|
|
|
|
trackEvent.StartPositionTicks -= startPositionTicks;
|
|
|
|
|
}
|
|
|
|
|
}
|
2014-06-11 12:31:33 -07:00
|
|
|
|
}
|
|
|
|
|
|
2014-06-11 07:42:03 -07:00
|
|
|
|
public async Task<Stream> GetSubtitles(string itemId,
|
|
|
|
|
string mediaSourceId,
|
|
|
|
|
int subtitleStreamIndex,
|
|
|
|
|
string outputFormat,
|
2014-06-11 12:31:33 -07:00
|
|
|
|
long startTimeTicks,
|
2014-08-05 16:59:24 -07:00
|
|
|
|
long? endTimeTicks,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
var subtitle = await GetSubtitleStream(itemId, mediaSourceId, subtitleStreamIndex, cancellationToken)
|
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
using (var stream = subtitle.Item1)
|
|
|
|
|
{
|
|
|
|
|
var inputFormat = subtitle.Item2;
|
|
|
|
|
|
2014-08-05 16:59:24 -07:00
|
|
|
|
return await ConvertSubtitles(stream, inputFormat, outputFormat, startTimeTicks, endTimeTicks, cancellationToken).ConfigureAwait(false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task<Tuple<Stream, string>> GetSubtitleStream(string itemId,
|
|
|
|
|
string mediaSourceId,
|
|
|
|
|
int subtitleStreamIndex,
|
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
var item = (Video)_libraryManager.GetItemById(new Guid(itemId));
|
|
|
|
|
|
|
|
|
|
var mediaSource = item.GetMediaSources(false)
|
|
|
|
|
.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)
|
|
|
|
|
{
|
2014-06-16 18:56:23 -07:00
|
|
|
|
if (mediaSource.VideoType.Value == VideoType.BluRay ||
|
|
|
|
|
mediaSource.VideoType.Value == VideoType.Dvd)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
|
|
|
|
var mediaSourceItem = (Video)_libraryManager.GetItemById(new Guid(mediaSourceId));
|
|
|
|
|
inputFiles = mediaSourceItem.GetPlayableStreamFiles().ToArray();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2014-06-16 18:56:23 -07:00
|
|
|
|
var fileInfo = await GetReadableFile(mediaSource.Path, inputFiles, mediaSource.Protocol, subtitleStream, cancellationToken).ConfigureAwait(false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
2014-09-05 21:21:23 -07:00
|
|
|
|
var stream = await GetSubtitleStream(fileInfo.Item1, subtitleStream.Language, fileInfo.Item3).ConfigureAwait(false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
return new Tuple<Stream, string>(stream, fileInfo.Item2);
|
|
|
|
|
}
|
|
|
|
|
|
2014-09-05 21:21:23 -07:00
|
|
|
|
private async Task<Stream> GetSubtitleStream(string path, string language, bool requiresCharset)
|
2014-06-11 12:31:33 -07:00
|
|
|
|
{
|
2014-09-05 21:21:23 -07:00
|
|
|
|
if (requiresCharset && !string.IsNullOrEmpty(language))
|
2014-06-11 12:31:33 -07:00
|
|
|
|
{
|
|
|
|
|
var charset = GetSubtitleFileCharacterSet(path, language);
|
|
|
|
|
|
|
|
|
|
if (!string.IsNullOrEmpty(charset))
|
|
|
|
|
{
|
|
|
|
|
using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
|
|
|
|
|
{
|
|
|
|
|
using (var reader = new StreamReader(fs, Encoding.GetEncoding(charset)))
|
|
|
|
|
{
|
|
|
|
|
var text = await reader.ReadToEndAsync().ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
var bytes = Encoding.UTF8.GetBytes(text);
|
|
|
|
|
|
|
|
|
|
return new MemoryStream(bytes);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return File.OpenRead(path);
|
|
|
|
|
}
|
|
|
|
|
|
2014-09-05 21:21:23 -07:00
|
|
|
|
private async Task<Tuple<string, string, bool>> GetReadableFile(string mediaPath,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
string[] inputFiles,
|
2014-06-16 18:56:23 -07:00
|
|
|
|
MediaProtocol protocol,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
MediaStream subtitleStream,
|
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
if (!subtitleStream.IsExternal)
|
|
|
|
|
{
|
2014-08-30 08:12:28 -07:00
|
|
|
|
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";
|
|
|
|
|
}
|
|
|
|
|
|
2014-06-11 07:42:03 -07:00
|
|
|
|
// Extract
|
2014-08-30 08:12:28 -07:00
|
|
|
|
var outputPath = GetSubtitleCachePath(mediaPath, subtitleStream.Index, "." + outputFormat);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
2014-08-30 08:12:28 -07:00
|
|
|
|
await ExtractTextSubtitle(inputFiles, protocol, subtitleStream.Index, outputCodec, outputPath, cancellationToken)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
|
2014-09-05 21:21:23 -07:00
|
|
|
|
return new Tuple<string, string, bool>(outputPath, outputFormat, false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var currentFormat = (Path.GetExtension(subtitleStream.Path) ?? subtitleStream.Codec)
|
|
|
|
|
.TrimStart('.');
|
|
|
|
|
|
|
|
|
|
if (GetReader(currentFormat, false) == null)
|
|
|
|
|
{
|
|
|
|
|
// Convert
|
2014-08-30 08:12:28 -07:00
|
|
|
|
var outputPath = GetSubtitleCachePath(mediaPath, subtitleStream.Index, ".srt");
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
2014-08-24 14:07:04 -07:00
|
|
|
|
await ConvertTextSubtitleToSrt(subtitleStream.Path, outputPath, subtitleStream.Language, cancellationToken)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
.ConfigureAwait(false);
|
|
|
|
|
|
2014-11-04 05:41:12 -07:00
|
|
|
|
return new Tuple<string, string, bool>(outputPath, "srt", true);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
|
2014-11-04 05:41:12 -07:00
|
|
|
|
return new Tuple<string, string, bool>(subtitleStream.Path, currentFormat, true);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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();
|
|
|
|
|
}
|
2014-08-21 19:24:38 -07:00
|
|
|
|
if (string.Equals(format, SubtitleFormat.SSA, StringComparison.OrdinalIgnoreCase))
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
|
|
|
|
return new SsaParser();
|
|
|
|
|
}
|
2014-08-21 19:24:38 -07:00
|
|
|
|
if (string.Equals(format, SubtitleFormat.ASS, StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return new AssParser();
|
|
|
|
|
}
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
if (throwIfMissing)
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentException("Unsupported format: " + format);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private ISubtitleWriter GetWriter(string format)
|
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(format))
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("format");
|
|
|
|
|
}
|
|
|
|
|
|
2014-08-22 08:47:44 -07:00
|
|
|
|
if (string.Equals(format, "json", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return new JsonWriter(_json);
|
|
|
|
|
}
|
2014-06-11 13:57:18 -07:00
|
|
|
|
if (string.Equals(format, SubtitleFormat.SRT, StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return new SrtWriter();
|
|
|
|
|
}
|
2014-06-11 07:42:03 -07:00
|
|
|
|
if (string.Equals(format, SubtitleFormat.VTT, StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return new VttWriter();
|
|
|
|
|
}
|
2014-08-05 16:59:24 -07:00
|
|
|
|
if (string.Equals(format, SubtitleFormat.TTML, StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return new TtmlWriter();
|
|
|
|
|
}
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
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>
|
2014-08-24 14:07:04 -07:00
|
|
|
|
/// Converts the text subtitle to SRT.
|
2014-06-11 07:42:03 -07:00
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="inputPath">The input path.</param>
|
|
|
|
|
/// <param name="outputPath">The output path.</param>
|
|
|
|
|
/// <param name="language">The language.</param>
|
|
|
|
|
/// <param name="cancellationToken">The cancellation token.</param>
|
|
|
|
|
/// <returns>Task.</returns>
|
2014-08-24 14:07:04 -07:00
|
|
|
|
public async Task ConvertTextSubtitleToSrt(string inputPath, string outputPath, string language,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
var semaphore = GetLock(outputPath);
|
|
|
|
|
|
|
|
|
|
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (!File.Exists(outputPath))
|
|
|
|
|
{
|
2014-08-24 14:07:04 -07:00
|
|
|
|
await ConvertTextSubtitleToSrtInternal(inputPath, outputPath, language).ConfigureAwait(false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
semaphore.Release();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2014-08-24 14:07:04 -07:00
|
|
|
|
/// Converts the text subtitle to SRT internal.
|
2014-06-11 07:42:03 -07:00
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="inputPath">The input path.</param>
|
|
|
|
|
/// <param name="outputPath">The output path.</param>
|
|
|
|
|
/// <param name="language">The language.</param>
|
|
|
|
|
/// <returns>Task.</returns>
|
2014-08-24 14:07:04 -07:00
|
|
|
|
/// <exception cref="System.ArgumentNullException">
|
|
|
|
|
/// inputPath
|
2014-06-11 07:42:03 -07:00
|
|
|
|
/// or
|
2014-08-24 14:07:04 -07:00
|
|
|
|
/// outputPath
|
|
|
|
|
/// </exception>
|
2014-06-11 07:42:03 -07:00
|
|
|
|
/// <exception cref="System.ApplicationException"></exception>
|
2014-08-24 14:07:04 -07:00
|
|
|
|
private async Task ConvertTextSubtitleToSrtInternal(string inputPath, string outputPath, string language)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(inputPath))
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("inputPath");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(outputPath))
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("outputPath");
|
|
|
|
|
}
|
|
|
|
|
|
2014-06-11 12:31:33 -07:00
|
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
var encodingParam = string.IsNullOrEmpty(language)
|
|
|
|
|
? string.Empty
|
2014-06-11 12:31:33 -07:00
|
|
|
|
: GetSubtitleFileCharacterSet(inputPath, language);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
if (!string.IsNullOrEmpty(encodingParam))
|
|
|
|
|
{
|
|
|
|
|
encodingParam = " -sub_charenc " + encodingParam;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var process = new Process
|
|
|
|
|
{
|
|
|
|
|
StartInfo = new ProcessStartInfo
|
|
|
|
|
{
|
|
|
|
|
RedirectStandardOutput = false,
|
|
|
|
|
RedirectStandardError = true,
|
2014-06-29 10:35:05 -07:00
|
|
|
|
RedirectStandardInput = true,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
CreateNoWindow = true,
|
|
|
|
|
UseShellExecute = false,
|
|
|
|
|
FileName = _mediaEncoder.EncoderPath,
|
2014-08-24 14:07:04 -07:00
|
|
|
|
Arguments = string.Format("{0} -i \"{1}\" -c:s srt \"{2}\"", encodingParam, inputPath, outputPath),
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
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");
|
|
|
|
|
|
2014-06-29 10:35:05 -07:00
|
|
|
|
process.StandardInput.WriteLine("q");
|
2014-06-11 07:42:03 -07:00
|
|
|
|
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);
|
|
|
|
|
File.Delete(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>
|
2014-06-16 18:56:23 -07:00
|
|
|
|
/// <param name="protocol">The protocol.</param>
|
2014-06-11 07:42:03 -07:00
|
|
|
|
/// <param name="subtitleStreamIndex">Index of the subtitle stream.</param>
|
2014-08-30 07:26:29 -07:00
|
|
|
|
/// <param name="outputCodec">The output codec.</param>
|
2014-06-11 07:42:03 -07:00
|
|
|
|
/// <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>
|
2014-06-16 18:56:23 -07:00
|
|
|
|
private async Task ExtractTextSubtitle(string[] inputFiles, MediaProtocol protocol, int subtitleStreamIndex,
|
2014-08-30 07:26:29 -07:00
|
|
|
|
string outputCodec, string outputPath, CancellationToken cancellationToken)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
|
|
|
|
var semaphore = GetLock(outputPath);
|
|
|
|
|
|
|
|
|
|
await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
if (!File.Exists(outputPath))
|
|
|
|
|
{
|
2014-06-16 18:56:23 -07:00
|
|
|
|
await ExtractTextSubtitleInternal(_mediaEncoder.GetInputArgument(inputFiles, protocol), subtitleStreamIndex,
|
2014-08-30 07:26:29 -07:00
|
|
|
|
outputCodec, outputPath, cancellationToken).ConfigureAwait(false);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
semaphore.Release();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex,
|
2014-08-30 07:26:29 -07:00
|
|
|
|
string outputCodec, string outputPath, CancellationToken cancellationToken)
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrEmpty(inputPath))
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("inputPath");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(outputPath))
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentNullException("outputPath");
|
|
|
|
|
}
|
|
|
|
|
|
2014-06-11 12:31:33 -07:00
|
|
|
|
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
|
|
|
|
|
|
2014-08-30 07:26:29 -07:00
|
|
|
|
var processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s {2} \"{3}\"", inputPath,
|
|
|
|
|
subtitleStreamIndex, outputCodec, outputPath);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
var process = new Process
|
|
|
|
|
{
|
|
|
|
|
StartInfo = new ProcessStartInfo
|
|
|
|
|
{
|
|
|
|
|
CreateNoWindow = true,
|
|
|
|
|
UseShellExecute = false,
|
|
|
|
|
|
|
|
|
|
RedirectStandardOutput = false,
|
|
|
|
|
RedirectStandardError = true,
|
2014-06-29 10:35:05 -07:00
|
|
|
|
RedirectStandardInput = true,
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
FileName = _mediaEncoder.EncoderPath,
|
|
|
|
|
Arguments = processArgs,
|
|
|
|
|
WindowStyle = ProcessWindowStyle.Hidden,
|
|
|
|
|
ErrorDialog = false
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2014-12-16 22:30:31 -07:00
|
|
|
|
_logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
|
|
|
|
|
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");
|
|
|
|
|
|
2014-06-29 10:35:05 -07:00
|
|
|
|
process.StandardInput.WriteLine("q");
|
2014-06-11 07:42:03 -07:00
|
|
|
|
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;
|
|
|
|
|
|
2014-12-16 22:30:31 -07:00
|
|
|
|
try
|
2014-06-11 07:42:03 -07:00
|
|
|
|
{
|
2014-12-16 22:30:31 -07:00
|
|
|
|
_logger.Info("Deleting extracted subtitle due to failure: {0}", outputPath);
|
|
|
|
|
File.Delete(outputPath);
|
|
|
|
|
}
|
|
|
|
|
catch (FileNotFoundException)
|
|
|
|
|
{
|
2015-01-10 12:42:14 -07:00
|
|
|
|
|
2014-12-22 20:58:14 -07:00
|
|
|
|
}
|
|
|
|
|
catch (DirectoryNotFoundException)
|
|
|
|
|
{
|
|
|
|
|
|
2014-12-16 22:30:31 -07:00
|
|
|
|
}
|
|
|
|
|
catch (IOException ex)
|
|
|
|
|
{
|
|
|
|
|
_logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath);
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
2014-09-05 21:21:23 -07:00
|
|
|
|
if (string.Equals(outputCodec, "ass", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
await SetAssFont(outputPath).ConfigureAwait(false);
|
|
|
|
|
}
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <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, int subtitleStreamIndex, string outputSubtitleExtension)
|
|
|
|
|
{
|
|
|
|
|
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);
|
|
|
|
|
}
|
2014-06-11 12:31:33 -07:00
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Gets the subtitle language encoding param.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="path">The path.</param>
|
|
|
|
|
/// <param name="language">The language.</param>
|
|
|
|
|
/// <returns>System.String.</returns>
|
|
|
|
|
public string GetSubtitleFileCharacterSet(string path, string language)
|
|
|
|
|
{
|
2015-01-11 19:12:47 -07:00
|
|
|
|
var charset = DetectCharset(path);
|
2015-01-10 12:42:14 -07:00
|
|
|
|
|
2015-01-11 19:12:47 -07:00
|
|
|
|
if (!string.IsNullOrWhiteSpace(charset))
|
|
|
|
|
{
|
|
|
|
|
if (string.Equals(charset, "utf-8", StringComparison.OrdinalIgnoreCase))
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
2015-01-10 12:42:14 -07:00
|
|
|
|
|
2015-01-11 19:12:47 -07:00
|
|
|
|
return charset;
|
|
|
|
|
}
|
2015-01-10 12:42:14 -07:00
|
|
|
|
|
2014-06-11 12:31:33 -07:00
|
|
|
|
if (GetFileEncoding(path).Equals(Encoding.UTF8))
|
|
|
|
|
{
|
|
|
|
|
return string.Empty;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-01-10 12:42:14 -07:00
|
|
|
|
private string DetectCharset(string path)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using (var file = new FileStream(path, FileMode.Open))
|
|
|
|
|
{
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
|
2014-06-11 12:31:33 -07:00
|
|
|
|
private static Encoding GetFileEncoding(string srcFile)
|
|
|
|
|
{
|
|
|
|
|
// *** Detect byte order mark if any - otherwise assume default
|
|
|
|
|
var buffer = new byte[5];
|
|
|
|
|
|
|
|
|
|
using (var file = new FileStream(srcFile, FileMode.Open))
|
|
|
|
|
{
|
|
|
|
|
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;
|
|
|
|
|
}
|
2014-06-11 07:42:03 -07:00
|
|
|
|
}
|
|
|
|
|
}
|