aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Api/HttpHandlers/VideoHandler.cs
blob: 9d52136f0ac29920841c678333c103b760e43061 (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
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
using MediaBrowser.Common.Drawing;
using MediaBrowser.Common.Net.Handlers;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.DTO;
using MediaBrowser.Model.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;

namespace MediaBrowser.Api.HttpHandlers
{
    /// <summary>
    /// Supported output formats: mkv,m4v,mp4,asf,wmv,mov,webm,ogv,3gp,avi,ts,flv
    /// </summary>
    [Export(typeof(BaseHandler))]
    class VideoHandler : BaseMediaHandler<Video, VideoOutputFormats>
    {
        public override bool HandlesRequest(HttpListenerRequest request)
        {
            return ApiService.IsApiUrlMatch("video", request);
        }

        /// <summary>
        /// We can output these files directly, but we can't encode them
        /// </summary>
        protected override IEnumerable<VideoOutputFormats> UnsupportedOutputEncodingFormats
        {
            get
            {
                // mp4, 3gp, mov - muxer does not support non-seekable output
                // avi, mov, mkv, m4v - can't stream these when encoding. the player will try to download them completely before starting playback.
                // wmv - can't seem to figure out the output format name
                return new VideoOutputFormats[] { VideoOutputFormats.Mp4, VideoOutputFormats.ThreeGp, VideoOutputFormats.M4V, VideoOutputFormats.Mkv, VideoOutputFormats.Avi, VideoOutputFormats.Mov, VideoOutputFormats.Wmv };
            }
        }

        /// <summary>
        /// Determines whether or not we can just output the original file directly
        /// </summary>
        protected override bool RequiresConversion()
        {
            if (base.RequiresConversion())
            {
                return true;
            }

            // See if the video requires conversion
            if (RequiresVideoConversion())
            {
                return true;
            }

            // See if the audio requires conversion
            AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();

            if (audioStream != null)
            {
                if (RequiresAudioConversion(audioStream))
                {
                    return true;
                }
            }

            // Yay
            return false;
        }

        /// <summary>
        /// Translates the output file extension to the format param that follows "-f" on the ffmpeg command line
        /// </summary>
        private string GetFfMpegOutputFormat(VideoOutputFormats outputFormat)
        {
            if (outputFormat == VideoOutputFormats.Mkv)
            {
                return "matroska";
            }
            if (outputFormat == VideoOutputFormats.Ts)
            {
                return "mpegts";
            }
            if (outputFormat == VideoOutputFormats.Ogv)
            {
                return "ogg";
            }

            return outputFormat.ToString().ToLower();
        }

        /// <summary>
        /// Creates arguments to pass to ffmpeg
        /// </summary>
        protected override string GetCommandLineArguments()
        {
            VideoOutputFormats outputFormat = GetConversionOutputFormat();

            return string.Format("-i \"{0}\" -threads 0 {1} {2} -f {3} -",
                LibraryItem.Path,
                GetVideoArguments(outputFormat),
                GetAudioArguments(outputFormat),
                GetFfMpegOutputFormat(outputFormat)
                );
        }

        /// <summary>
        /// Gets video arguments to pass to ffmpeg
        /// </summary>
        private string GetVideoArguments(VideoOutputFormats outputFormat)
        {
            // Get the output codec name
            string codec = GetVideoCodec(outputFormat);

            string args = "-vcodec " + codec;

            // If we're encoding video, add additional params
            if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
            {
                // Add resolution params, if specified
                if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
                {
                    Size size = DrawingUtils.Resize(LibraryItem.Width, LibraryItem.Height, Width, Height, MaxWidth, MaxHeight);

                    args += string.Format(" -s {0}x{1}", size.Width, size.Height);
                }
            }

            return args;
        }

        /// <summary>
        /// Gets audio arguments to pass to ffmpeg
        /// </summary>
        private string GetAudioArguments(VideoOutputFormats outputFormat)
        {
            AudioStream audioStream = (LibraryItem.AudioStreams ?? new List<AudioStream>()).FirstOrDefault();

            // If the video doesn't have an audio stream, return empty
            if (audioStream == null)
            {
                return string.Empty;
            }

            // Get the output codec name
            string codec = GetAudioCodec(audioStream, outputFormat);

            string args = "-acodec " + codec;

            // If we're encoding audio, add additional params
            if (!codec.Equals("copy", StringComparison.OrdinalIgnoreCase))
            {
                // Add the number of audio channels
                int? channels = GetNumAudioChannelsParam(codec, audioStream.Channels);

                if (channels.HasValue)
                {
                    args += " -ac " + channels.Value;
                }

                // Add the audio sample rate
                int? sampleRate = GetSampleRateParam(audioStream.SampleRate);

                if (sampleRate.HasValue)
                {
                    args += " -ar " + sampleRate.Value;
                }

            }

            return args;
        }

        /// <summary>
        /// Gets the name of the output video codec
        /// </summary>
        private string GetVideoCodec(VideoOutputFormats outputFormat)
        {
            // Some output containers require specific codecs

            if (outputFormat == VideoOutputFormats.Webm)
            {
                // Per webm specification, it must be vpx
                return "libvpx";
            }
            if (outputFormat == VideoOutputFormats.Asf)
            {
                return "wmv2";
            }
            if (outputFormat == VideoOutputFormats.Wmv)
            {
                return "wmv2";
            }
            if (outputFormat == VideoOutputFormats.Ogv)
            {
                return "libtheora";
            }

            // Skip encoding when possible
            if (!RequiresVideoConversion())
            {
                return "copy";
            }

            return "libx264";
        }

        /// <summary>
        /// Gets the name of the output audio codec
        /// </summary>
        private string GetAudioCodec(AudioStream audioStream, VideoOutputFormats outputFormat)
        {
            // Some output containers require specific codecs

            if (outputFormat == VideoOutputFormats.Webm)
            {
                // Per webm specification, it must be vorbis
                return "libvorbis";
            }
            if (outputFormat == VideoOutputFormats.Asf)
            {
                return "wmav2";
            }
            if (outputFormat == VideoOutputFormats.Wmv)
            {
                return "wmav2";
            }
            if (outputFormat == VideoOutputFormats.Ogv)
            {
                return "libvorbis";
            }

            // Skip encoding when possible
            if (!RequiresAudioConversion(audioStream))
            {
                return "copy";
            }

            return "libvo_aacenc";
        }

        /// <summary>
        /// Gets the number of audio channels to specify on the command line
        /// </summary>
        private int? GetNumAudioChannelsParam(string audioCodec, int libraryItemChannels)
        {
            if (libraryItemChannels > 2)
            {
                if (audioCodec.Equals("libvo_aacenc"))
                {
                    // libvo_aacenc currently only supports two channel output
                    return 2;
                }
                if (audioCodec.Equals("wmav2"))
                {
                    // wmav2 currently only supports two channel output
                    return 2;
                }
            }

            return GetNumAudioChannelsParam(libraryItemChannels);
        }

        /// <summary>
        /// Determines if the video stream requires encoding
        /// </summary>
        private bool RequiresVideoConversion()
        {
            // Check dimensions

            // If a specific width is required, validate that
            if (Width.HasValue)
            {
                if (Width.Value != LibraryItem.Width)
                {
                    return true;
                }
            }

            // If a specific height is required, validate that
            if (Height.HasValue)
            {
                if (Height.Value != LibraryItem.Height)
                {
                    return true;
                }
            }

            // If a max width is required, validate that
            if (MaxWidth.HasValue)
            {
                if (MaxWidth.Value < LibraryItem.Width)
                {
                    return true;
                }
            }

            // If a max height is required, validate that
            if (MaxHeight.HasValue)
            {
                if (MaxHeight.Value < LibraryItem.Height)
                {
                    return true;
                }
            }

            // If the codec is already h264, don't encode
            if (LibraryItem.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 || LibraryItem.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1)
            {
                return false;
            }

            return false;
        }

        /// <summary>
        /// Determines if the audio stream requires encoding
        /// </summary>
        private bool RequiresAudioConversion(AudioStream audio)
        {

            // If the input stream has more audio channels than the client can handle, we need to encode
            if (AudioChannels.HasValue)
            {
                if (audio.Channels > AudioChannels.Value)
                {
                    return true;
                }
            }

            // Aac, ac-3 and mp3 are all pretty much universally supported. No need to encode them

            if (audio.Codec.IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)
            {
                return false;
            }

            if (audio.Codec.IndexOf("ac-3", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("ac3", StringComparison.OrdinalIgnoreCase) != -1)
            {
                return false;
            }

            if (audio.Codec.IndexOf("mpeg", StringComparison.OrdinalIgnoreCase) != -1 || audio.Codec.IndexOf("mp3", StringComparison.OrdinalIgnoreCase) != -1)
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// Gets the fixed output video height, in pixels
        /// </summary>
        private int? Height
        {
            get
            {
                string val = QueryString["height"];

                if (string.IsNullOrEmpty(val))
                {
                    return null;
                }

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the fixed output video width, in pixels
        /// </summary>
        private int? Width
        {
            get
            {
                string val = QueryString["width"];

                if (string.IsNullOrEmpty(val))
                {
                    return null;
                }

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the maximum output video height, in pixels
        /// </summary>
        private int? MaxHeight
        {
            get
            {
                string val = QueryString["maxheight"];

                if (string.IsNullOrEmpty(val))
                {
                    return null;
                }

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the maximum output video width, in pixels
        /// </summary>
        private int? MaxWidth
        {
            get
            {
                string val = QueryString["maxwidth"];

                if (string.IsNullOrEmpty(val))
                {
                    return null;
                }

                return int.Parse(val);
            }
        }

    }
}