aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.MediaEncoding/Subtitles/SrtWriter.cs
blob: 86f77aa067ae5440b96a0ae12c3c711254a3eb6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
{
    /// <summary>
    /// SRT subtitle writer.
    /// </summary>
    public partial class SrtWriter : ISubtitleWriter
    {
        [GeneratedRegex(@"\\n", RegexOptions.IgnoreCase)]
        private static partial Regex NewLineEscapedRegex();

        /// <inheritdoc />
        public void Write(SubtitleTrackInfo info, Stream stream, CancellationToken cancellationToken)
        {
            using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
            {
                var trackEvents = info.TrackEvents;

                for (int i = 0; i < trackEvents.Count; i++)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var trackEvent = trackEvents[i];

                    writer.WriteLine((i + 1).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 = NewLineEscapedRegex().Replace(text, " ");

                    writer.WriteLine(text);
                    writer.WriteLine();
                }
            }
        }
    }
}