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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
|
using MediaBrowser.Common.IO;
using MediaBrowser.Common.MediaInfo;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Movies;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.MediaInfo;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Controller.Providers.MediaInfo
{
/// <summary>
/// Extracts video information using ffprobe
/// </summary>
public class FFProbeVideoInfoProvider : BaseFFProbeProvider<Video>
{
public FFProbeVideoInfoProvider(IIsoManager isoManager, IBlurayExaminer blurayExaminer, IJsonSerializer jsonSerializer, ILogManager logManager, IServerConfigurationManager configurationManager, IMediaEncoder mediaEncoder)
: base(logManager, configurationManager, mediaEncoder, jsonSerializer)
{
if (isoManager == null)
{
throw new ArgumentNullException("isoManager");
}
if (blurayExaminer == null)
{
throw new ArgumentNullException("blurayExaminer");
}
_blurayExaminer = blurayExaminer;
_isoManager = isoManager;
BdInfoCache = new FileSystemRepository(Path.Combine(ConfigurationManager.ApplicationPaths.CachePath, "bdinfo"));
}
/// <summary>
/// Gets or sets the bd info cache.
/// </summary>
/// <value>The bd info cache.</value>
private FileSystemRepository BdInfoCache { get; set; }
/// <summary>
/// Gets or sets the bluray examiner.
/// </summary>
/// <value>The bluray examiner.</value>
private readonly IBlurayExaminer _blurayExaminer;
/// <summary>
/// The _iso manager
/// </summary>
private readonly IIsoManager _isoManager;
/// <summary>
/// Returns true or false indicating if the provider should refresh when the contents of it's directory changes
/// </summary>
/// <value><c>true</c> if [refresh on file system stamp change]; otherwise, <c>false</c>.</value>
protected override bool RefreshOnFileSystemStampChange
{
get
{
return true;
}
}
/// <summary>
/// Supports video files and dvd structures
/// </summary>
/// <param name="item">The item.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
public override bool Supports(BaseItem item)
{
if (item.LocationType != LocationType.FileSystem)
{
return false;
}
var video = item as Video;
if (video != null)
{
if (video.VideoType == VideoType.Iso)
{
return _isoManager.CanMount(item.Path);
}
return video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay;
}
return false;
}
/// <summary>
/// Called when [pre fetch].
/// </summary>
/// <param name="item">The item.</param>
/// <param name="mount">The mount.</param>
protected override void OnPreFetch(Video item, IIsoMount mount)
{
if (item.VideoType == VideoType.Iso)
{
item.IsoType = DetermineIsoType(mount);
}
if (item.VideoType == VideoType.Dvd || (item.IsoType.HasValue && item.IsoType == IsoType.Dvd))
{
PopulateDvdStreamFiles(item, mount);
}
base.OnPreFetch(item, mount);
}
/// <summary>
/// Mounts the iso if needed.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>IsoMount.</returns>
protected override Task<IIsoMount> MountIsoIfNeeded(Video item, CancellationToken cancellationToken)
{
if (item.VideoType == VideoType.Iso)
{
return _isoManager.Mount(item.Path, cancellationToken);
}
return base.MountIsoIfNeeded(item, cancellationToken);
}
/// <summary>
/// Determines the type of the iso.
/// </summary>
/// <param name="isoMount">The iso mount.</param>
/// <returns>System.Nullable{IsoType}.</returns>
private IsoType? DetermineIsoType(IIsoMount isoMount)
{
var folders = Directory.EnumerateDirectories(isoMount.MountedPath).Select(Path.GetFileName).ToList();
if (folders.Contains("video_ts", StringComparer.OrdinalIgnoreCase))
{
return IsoType.Dvd;
}
if (folders.Contains("bdmv", StringComparer.OrdinalIgnoreCase))
{
return IsoType.BluRay;
}
return null;
}
/// <summary>
/// Finds vob files and populates the dvd stream file properties
/// </summary>
/// <param name="video">The video.</param>
/// <param name="isoMount">The iso mount.</param>
private void PopulateDvdStreamFiles(Video video, IIsoMount isoMount)
{
// min size 300 mb
const long minPlayableSize = 314572800;
var root = isoMount != null ? isoMount.MountedPath : video.Path;
// Try to eliminate menus and intros by skipping all files at the front of the list that are less than the minimum size
// Once we reach a file that is at least the minimum, return all subsequent ones
var files = Directory.EnumerateFiles(root, "*.vob", SearchOption.AllDirectories).SkipWhile(f => new FileInfo(f).Length < minPlayableSize).ToList();
// Assuming they're named "vts_05_01", take all files whose second part matches that of the first file
if (files.Count > 0)
{
var parts = Path.GetFileNameWithoutExtension(files[0]).Split('_');
if (parts.Length == 3)
{
var title = parts[1];
files = files.TakeWhile(f =>
{
var fileParts = Path.GetFileNameWithoutExtension(f).Split('_');
return fileParts.Length == 3 && string.Equals(title, fileParts[1], StringComparison.OrdinalIgnoreCase);
}).ToList();
}
}
video.PlayableStreamFileNames = files.Select(Path.GetFileName).ToList();
}
/// <summary>
/// Fetches the specified video.
/// </summary>
/// <param name="video">The video.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <param name="data">The data.</param>
/// <param name="isoMount">The iso mount.</param>
/// <returns>Task.</returns>
protected override void Fetch(Video video, CancellationToken cancellationToken, MediaInfoResult data, IIsoMount isoMount)
{
if (data.format != null)
{
// For dvd's this may not always be accurate, so don't set the runtime if the item already has one
var needToSetRuntime = video.VideoType != VideoType.Dvd || video.RunTimeTicks == null || video.RunTimeTicks.Value == 0;
if (needToSetRuntime && !string.IsNullOrEmpty(data.format.duration))
{
video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, UsCulture)).Ticks;
}
}
if (data.streams != null)
{
video.MediaStreams = data.streams.Select(s => GetMediaStream(s, data.format)).ToList();
}
if (data.Chapters != null)
{
video.Chapters = data.Chapters;
}
if (video.Chapters == null || video.Chapters.Count == 0)
{
AddDummyChapters(video);
}
if (video.VideoType == VideoType.BluRay || (video.IsoType.HasValue && video.IsoType.Value == IsoType.BluRay))
{
var inputPath = isoMount != null ? isoMount.MountedPath : video.Path;
FetchBdInfo(video, inputPath, BdInfoCache, cancellationToken);
}
AddExternalSubtitles(video);
}
/// <summary>
/// Adds the external subtitles.
/// </summary>
/// <param name="video">The video.</param>
private void AddExternalSubtitles(Video video)
{
var useParent = (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso) && !(video is Movie);
if (useParent && video.Parent == null)
{
return;
}
var fileSystemChildren = useParent
? video.Parent.ResolveArgs.FileSystemChildren
: video.ResolveArgs.FileSystemChildren;
var startIndex = video.MediaStreams == null ? 0 : video.MediaStreams.Count;
var streams = new List<MediaStream>();
foreach (var file in fileSystemChildren.Where(f => !f.IsDirectory))
{
var extension = Path.GetExtension(file.Path);
if (string.Equals(extension, ".srt", StringComparison.OrdinalIgnoreCase))
{
if (video.VideoType == VideoType.VideoFile)
{
// For video files the subtitle filename must match video filename
if (!string.Equals(Path.GetFileNameWithoutExtension(video.Path), Path.GetFileNameWithoutExtension(file.Path)))
{
continue;
}
}
streams.Add(new MediaStream
{
Index = startIndex++,
Type = MediaStreamType.Subtitle,
IsExternal = true,
Path = file.Path,
Codec = "srt"
});
}
}
if (video.MediaStreams == null)
{
video.MediaStreams = new List<MediaStream>();
}
video.MediaStreams.AddRange(streams);
}
/// <summary>
/// The dummy chapter duration
/// </summary>
private readonly long DummyChapterDuration = TimeSpan.FromMinutes(10).Ticks;
/// <summary>
/// Adds the dummy chapters.
/// </summary>
/// <param name="video">The video.</param>
private void AddDummyChapters(Video video)
{
var runtime = video.RunTimeTicks ?? 0;
if (runtime < DummyChapterDuration)
{
return;
}
long currentChapterTicks = 0;
var index = 1;
var chapters = new List<ChapterInfo> { };
while (currentChapterTicks < runtime)
{
chapters.Add(new ChapterInfo
{
Name = "Chapter " + index,
StartPositionTicks = currentChapterTicks
});
index++;
currentChapterTicks += DummyChapterDuration;
}
video.Chapters = chapters;
}
/// <summary>
/// Fetches the bd info.
/// </summary>
/// <param name="item">The item.</param>
/// <param name="inputPath">The input path.</param>
/// <param name="bdInfoCache">The bd info cache.</param>
/// <param name="cancellationToken">The cancellation token.</param>
private void FetchBdInfo(BaseItem item, string inputPath, FileSystemRepository bdInfoCache, CancellationToken cancellationToken)
{
var video = (Video)item;
// Get the path to the cache file
var cacheName = item.Id + "_" + item.DateModified.Ticks;
var cacheFile = bdInfoCache.GetResourcePath(cacheName, ".js");
BlurayDiscInfo result;
try
{
result = JsonSerializer.DeserializeFromFile<BlurayDiscInfo>(cacheFile);
}
catch (FileNotFoundException)
{
result = GetBDInfo(inputPath);
JsonSerializer.SerializeToFile(result, cacheFile);
}
cancellationToken.ThrowIfCancellationRequested();
int? currentHeight = null;
int? currentWidth = null;
int? currentBitRate = null;
var videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
// Grab the values that ffprobe recorded
if (videoStream != null)
{
currentBitRate = videoStream.BitRate;
currentWidth = videoStream.Width;
currentHeight = videoStream.Height;
}
// Fill video properties from the BDInfo result
Fetch(video, inputPath, result);
videoStream = video.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
// Use the ffprobe values if these are empty
if (videoStream != null)
{
videoStream.BitRate = IsEmpty(videoStream.BitRate) ? currentBitRate : videoStream.BitRate;
videoStream.Width = IsEmpty(videoStream.Width) ? currentWidth : videoStream.Width;
videoStream.Height = IsEmpty(videoStream.Height) ? currentHeight : videoStream.Height;
}
}
/// <summary>
/// Determines whether the specified num is empty.
/// </summary>
/// <param name="num">The num.</param>
/// <returns><c>true</c> if the specified num is empty; otherwise, <c>false</c>.</returns>
private bool IsEmpty(int? num)
{
return !num.HasValue || num.Value == 0;
}
/// <summary>
/// Fills video properties from the VideoStream of the largest playlist
/// </summary>
/// <param name="video">The video.</param>
/// <param name="inputPath">The input path.</param>
/// <param name="stream">The stream.</param>
private void Fetch(Video video, string inputPath, BlurayDiscInfo stream)
{
// Check all input for null/empty/zero
video.MediaStreams = stream.MediaStreams;
if (stream.RunTimeTicks.HasValue && stream.RunTimeTicks.Value > 0)
{
video.RunTimeTicks = stream.RunTimeTicks;
}
video.PlayableStreamFileNames = stream.Files.ToList();
if (stream.Chapters != null)
{
video.Chapters = stream.Chapters.Select(c => new ChapterInfo
{
StartPositionTicks = TimeSpan.FromSeconds(c).Ticks
}).ToList();
}
}
/// <summary>
/// Gets information about the longest playlist on a bdrom
/// </summary>
/// <param name="path">The path.</param>
/// <returns>VideoStream.</returns>
private BlurayDiscInfo GetBDInfo(string path)
{
return _blurayExaminer.GetDiscInfo(path);
}
}
}
|