aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Controller/Providers/VideoInfoProvider.cs
blob: 8145654331a587f05756002004b0dff24d213ef1 (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
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading.Tasks;
using MediaBrowser.Controller.Events;
using MediaBrowser.Controller.FFMpeg;
using MediaBrowser.Model.Entities;

namespace MediaBrowser.Controller.Providers
{
    [Export(typeof(BaseMetadataProvider))]
    public class VideoInfoProvider : BaseMetadataProvider
    {
        public override bool Supports(BaseEntity item)
        {
            return item is Video;
        }

        public override MetadataProviderPriority Priority
        {
            // Give this second priority
            // Give metadata xml providers a chance to fill in data first, so that we can skip this whenever possible
            get { return MetadataProviderPriority.Second; }
        }

        public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args)
        {
            await Task.Run(() =>
            {
                Video video = item as Video;

                if (video.VideoType != VideoType.VideoFile)
                {
                    // Not supported yet
                    return;
                }

                if (CanSkip(video))
                {
                    return;
                }

                Fetch(video, FFProbe.Run(video));
            });
        }

        private void Fetch(Video video, FFProbeResult data)
        {
            if (!string.IsNullOrEmpty(data.format.duration))
            {
                video.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration)).Ticks;
            }

            if (!string.IsNullOrEmpty(data.format.bit_rate))
            {
                video.BitRate = int.Parse(data.format.bit_rate);
            }

            // For now, only read info about first video stream
            // Files with multiple video streams are possible, but extremely rare
            bool foundVideo = false;

            foreach (MediaStream stream in data.streams)
            {
                if (stream.codec_type.Equals("video", StringComparison.OrdinalIgnoreCase))
                {
                    if (!foundVideo)
                    {
                        FetchFromVideoStream(video, stream);
                    }

                    foundVideo = true;
                }
                else if (stream.codec_type.Equals("audio", StringComparison.OrdinalIgnoreCase))
                {
                    FetchFromAudioStream(video, stream);
                }
            }
        }

        private void FetchFromVideoStream(Video video, MediaStream stream)
        {
            video.Codec = stream.codec_name;
            video.Width = stream.width;
            video.Height = stream.height;
            video.AspectRatio = stream.display_aspect_ratio;

            if (!string.IsNullOrEmpty(stream.avg_frame_rate))
            {
                string[] parts = stream.avg_frame_rate.Split('/');

                if (parts.Length == 2)
                {
                    video.FrameRate = float.Parse(parts[0]) / float.Parse(parts[1]);
                }
                else
                {
                    video.FrameRate = float.Parse(parts[0]);
                }
            }
        }

        private void FetchFromAudioStream(Video video, MediaStream stream)
        {
            AudioStream audio = new AudioStream();

            audio.Codec = stream.codec_name;

            if (!string.IsNullOrEmpty(stream.bit_rate))
            {
                audio.BitRate = int.Parse(stream.bit_rate);
            }

            audio.Channels = stream.channels;

            if (!string.IsNullOrEmpty(stream.sample_rate))
            {
                audio.SampleRate = int.Parse(stream.sample_rate);
            }

            audio.Language = AudioInfoProvider.GetDictionaryValue(stream.tags, "language");

            List<AudioStream> streams = (video.AudioStreams ?? new AudioStream[] { }).ToList();
            streams.Add(audio);
            video.AudioStreams = streams;
        }
        
        /// <summary>
        /// Determines if there's already enough info in the Video object to allow us to skip running ffprobe
        /// </summary>
        private bool CanSkip(Video video)
        {
            if (video.AudioStreams == null || !video.AudioStreams.Any())
            {
                return false;
            }

            if (string.IsNullOrEmpty(video.AspectRatio))
            {
                return false;
            }

            if (string.IsNullOrEmpty(video.Codec))
            {
                return false;
            }

            if (string.IsNullOrEmpty(video.ScanType))
            {
                return false;
            }

            if (!video.RunTimeTicks.HasValue || video.RunTimeTicks.Value == 0)
            {
                return false;
            }

            if (video.FrameRate == 0 || video.Height == 0 || video.Width == 0 || video.BitRate == 0)
            {
                return false;
            }
            
            return true;
        }

        public override void Init()
        {
            base.Init();

            AudioInfoProvider.EnsureCacheSubFolders(Kernel.Instance.ApplicationPaths.FFProbeVideoCacheDirectory);
        }
    }
}