jellyfin/MediaBrowser.MediaEncoding/Subtitles/SubtitleEditParser.cs

62 lines
2.1 KiB
C#
Raw Normal View History

2021-01-08 15:03:02 -07:00
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using Jellyfin.Extensions;
2021-01-08 15:03:02 -07:00
using MediaBrowser.Model.MediaInfo;
2021-01-08 15:21:50 -07:00
using Microsoft.Extensions.Logging;
2021-09-13 05:32:26 -07:00
using Nikse.SubtitleEdit.Core.Common;
2021-01-08 15:21:50 -07:00
using ILogger = Microsoft.Extensions.Logging.ILogger;
using SubtitleFormat = Nikse.SubtitleEdit.Core.SubtitleFormats.SubtitleFormat;
2021-01-08 15:03:02 -07:00
namespace MediaBrowser.MediaEncoding.Subtitles
{
/// <summary>
/// SubStation Alpha subtitle parser.
/// </summary>
2021-01-08 15:21:50 -07:00
/// <typeparam name="T">The <see cref="SubtitleFormat" />.</typeparam>
2021-01-08 15:03:02 -07:00
public abstract class SubtitleEditParser<T> : ISubtitleParser
2021-01-08 15:21:50 -07:00
where T : SubtitleFormat, new()
2021-01-08 15:03:02 -07:00
{
2021-01-08 15:21:50 -07:00
private readonly ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="SubtitleEditParser{T}"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
protected SubtitleEditParser(ILogger logger)
{
_logger = logger;
}
2021-01-08 15:03:02 -07:00
/// <inheritdoc />
public SubtitleTrackInfo Parse(Stream stream, CancellationToken cancellationToken)
{
var subtitle = new Subtitle();
var subRip = new T();
var lines = stream.ReadAllLines().ToList();
subRip.LoadSubtitle(subtitle, lines, "untitled");
2021-01-08 15:21:50 -07:00
if (subRip.ErrorCount > 0)
{
2021-09-25 09:15:46 -07:00
_logger.LogError("{ErrorCount} errors encountered while parsing subtitle", subRip.ErrorCount);
2021-01-08 15:21:50 -07:00
}
2021-01-08 15:03:02 -07:00
var trackInfo = new SubtitleTrackInfo();
int len = subtitle.Paragraphs.Count;
var trackEvents = new SubtitleTrackEvent[len];
for (int i = 0; i < len; i++)
{
var p = subtitle.Paragraphs[i];
trackEvents[i] = new SubtitleTrackEvent(p.Number.ToString(CultureInfo.InvariantCulture), p.Text)
{
StartPositionTicks = p.StartTime.TimeSpan.Ticks,
EndPositionTicks = p.EndTime.TimeSpan.Ticks
};
}
trackInfo.TrackEvents = trackEvents;
return trackInfo;
}
}
}