aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Api/Playback/BifService.cs
blob: 181cdfe896df2b3cd5402cb496180fd3c3724996 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
using MediaBrowser.Common.IO;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.MediaEncoding;
using ServiceStack;
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Api.Playback
{
    [Route("/Videos/{Id}/index.bif", "GET")]
    public class GetBifFile
    {
        [ApiMember(Name = "MediaSourceId", Description = "The media version id, if playing an alternate version", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
        public string MediaSourceId { get; set; }

        [ApiMember(Name = "MaxWidth", Description = "Optional. The maximum horizontal resolution of the encoded video.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
        public int? MaxWidth { get; set; }

        [ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
        public string Id { get; set; }
    }

    public class BifService : BaseApiService
    {
        private readonly IServerApplicationPaths _appPaths;
        private readonly ILibraryManager _libraryManager;
        private readonly IMediaEncoder _mediaEncoder;
        private readonly IFileSystem _fileSystem;

        public BifService(IServerApplicationPaths appPaths, ILibraryManager libraryManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem)
        {
            _appPaths = appPaths;
            _libraryManager = libraryManager;
            _mediaEncoder = mediaEncoder;
            _fileSystem = fileSystem;
        }

        public object Get(GetBifFile request)
        {
            return ToStaticFileResult(GetBifFile(request).Result);
        }

        private async Task<string> GetBifFile(GetBifFile request)
        {
            var widthVal = request.MaxWidth.HasValue ? request.MaxWidth.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;

            var item = _libraryManager.GetItemById(request.Id);
            var mediaSources = ((IHasMediaSources)item).GetMediaSources(false).ToList();
            var mediaSource = mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId)) ?? mediaSources.First();

            var path = Path.Combine(_appPaths.ImageCachePath, "bif", request.Id, request.MediaSourceId, widthVal, "index.bif");

            if (File.Exists(path))
            {
                return path;
            }

            var protocol = mediaSource.Protocol;

            var inputPath = MediaEncoderHelpers.GetInputArgument(mediaSource.Path, protocol, null, mediaSource.PlayableStreamFileNames);

            var semaphore = GetLock(path);

            await semaphore.WaitAsync().ConfigureAwait(false);

            try
            {
                if (File.Exists(path))
                {
                    return path;
                }
                
                await _mediaEncoder.ExtractVideoImagesOnInterval(inputPath, protocol, mediaSource.Video3DFormat,
                        TimeSpan.FromSeconds(10), Path.GetDirectoryName(path), "img_", request.MaxWidth, CancellationToken.None)
                        .ConfigureAwait(false);

                var images = new DirectoryInfo(Path.GetDirectoryName(path))
                    .EnumerateFiles()
                    .Where(img => string.Equals(img.Extension, ".jpg", StringComparison.Ordinal))
                    .OrderBy(i => i.FullName)
                    .ToList();

                using (var fs = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                {
                    var magicNumber = new byte[] { 0x89, 0x42, 0x49, 0x46, 0x0d, 0x0a, 0x1a, 0x0a };
                    await fs.WriteAsync(magicNumber, 0, magicNumber.Length);

                    // version
                    var bytes = GetBytes(0);
                    await fs.WriteAsync(bytes, 0, bytes.Length);

                    // image count
                    bytes = GetBytes(images.Count);
                    await fs.WriteAsync(bytes, 0, bytes.Length);

                    // interval in ms
                    bytes = GetBytes(10000);
                    await fs.WriteAsync(bytes, 0, bytes.Length);

                    // reserved
                    for (var i = 20; i <= 63; i++)
                    {
                        bytes = new byte[] { 0x00 };
                        await fs.WriteAsync(bytes, 0, bytes.Length);
                    }

                    // write the bif index
                    var index = 0;
                    long imageOffset = 64 + (8 * images.Count) + 8;

                    foreach (var img in images)
                    {
                        bytes = GetBytes(index);
                        await fs.WriteAsync(bytes, 0, bytes.Length);

                        bytes = GetBytes(imageOffset);
                        await fs.WriteAsync(bytes, 0, bytes.Length);

                        imageOffset += img.Length;

                        index++;
                    }

                    bytes = new byte[] { 0xff, 0xff, 0xff, 0xff };
                    await fs.WriteAsync(bytes, 0, bytes.Length);

                    bytes = GetBytes(imageOffset);
                    await fs.WriteAsync(bytes, 0, bytes.Length);

                    // write the images
                    foreach (var img in images)
                    {
                        using (var imgStream = _fileSystem.GetFileStream(img.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
                        {
                            await imgStream.CopyToAsync(fs).ConfigureAwait(false);
                        }
                    }
                }

                return path;
            }
            finally
            {
                semaphore.Release();
            }
        }

        private byte[] GetBytes(int value)
        {
            byte[] bytes = BitConverter.GetBytes(value);
            if (!BitConverter.IsLittleEndian)
                Array.Reverse(bytes);
            return bytes;
        }

        private byte[] GetBytes(long value)
        {
            var intVal = Convert.ToInt32(value);
            return GetBytes(intVal);

            //byte[] bytes = BitConverter.GetBytes(value);
            //if (BitConverter.IsLittleEndian)
            //    Array.Reverse(bytes);
            //return bytes;
        }

        private static 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 static SemaphoreSlim GetLock(string filename)
        {
            return SemaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1));
        }
    }
}