aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Api/Streaming/BaseStreamingHandler.cs
blob: 27ccdeb15415206f362cba30d6332e1d3fa186a5 (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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Common.Net.Handlers;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Drawing;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace MediaBrowser.Api.Streaming
{
    /// <summary>
    /// Represents a common base class for both progressive and hls streaming
    /// </summary>
    /// <typeparam name="TBaseItemType">The type of the T base item type.</typeparam>
    public abstract class BaseStreamingHandler<TBaseItemType> : BaseHandler<Kernel>
        where TBaseItemType : BaseItem, IHasMediaStreams, new()
    {
        /// <summary>
        /// Gets the command line arguments.
        /// </summary>
        /// <param name="outputPath">The output path.</param>
        /// <param name="isoMount">The iso mount.</param>
        /// <returns>System.String.</returns>
        protected abstract string GetCommandLineArguments(string outputPath, IIsoMount isoMount);

        /// <summary>
        /// Gets or sets the log file stream.
        /// </summary>
        /// <value>The log file stream.</value>
        protected Stream LogFileStream { get; set; }

        /// <summary>
        /// Gets the type of the transcoding job.
        /// </summary>
        /// <value>The type of the transcoding job.</value>
        protected abstract TranscodingJobType TranscodingJobType { get; }

        /// <summary>
        /// Gets the output file extension.
        /// </summary>
        /// <value>The output file extension.</value>
        protected string OutputFileExtension
        {
            get
            {
                return Path.GetExtension(HttpListenerContext.Request.Url.LocalPath);
            }
        }

        /// <summary>
        /// Gets the output file path.
        /// </summary>
        /// <value>The output file path.</value>
        protected string OutputFilePath
        {
            get
            {
                return Path.Combine(Kernel.ApplicationPaths.FFMpegStreamCachePath, GetCommandLineArguments("dummy\\dummy", null).GetMD5() + OutputFileExtension.ToLower());
            }
        }

        /// <summary>
        /// Gets the audio codec to endoce to.
        /// </summary>
        /// <value>The audio encoding format.</value>
        protected virtual AudioCodecs? AudioCodec
        {
            get
            {
                if (string.IsNullOrEmpty(QueryString["audioCodec"]))
                {
                    return null;
                }

                return (AudioCodecs)Enum.Parse(typeof(AudioCodecs), QueryString["audioCodec"], true);
            }
        }

        /// <summary>
        /// Gets the video encoding codec.
        /// </summary>
        /// <value>The video codec.</value>
        protected VideoCodecs? VideoCodec
        {
            get
            {
                if (string.IsNullOrEmpty(QueryString["videoCodec"]))
                {
                    return null;
                }

                return (VideoCodecs)Enum.Parse(typeof(VideoCodecs), QueryString["videoCodec"], true);
            }
        }

        /// <summary>
        /// Gets the time, in ticks, in which playback should start
        /// </summary>
        /// <value>The start time ticks.</value>
        protected long? StartTimeTicks
        {
            get
            {
                string val = QueryString["StartTimeTicks"];

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

                return long.Parse(val);
            }
        }

        /// <summary>
        /// The fast seek offset seconds
        /// </summary>
        private const int FastSeekOffsetSeconds = 1;

        /// <summary>
        /// Gets the fast seek command line parameter.
        /// </summary>
        /// <value>The fast seek command line parameter.</value>
        protected string FastSeekCommandLineParameter
        {
            get
            {
                var time = StartTimeTicks;

                if (time.HasValue)
                {
                    var seconds = TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds;

                    if (seconds > 0)
                    {
                        return string.Format("-ss {0}", seconds);
                    }
                }

                return string.Empty;
            }
        }

        /// <summary>
        /// Gets the slow seek command line parameter.
        /// </summary>
        /// <value>The slow seek command line parameter.</value>
        protected string SlowSeekCommandLineParameter
        {
            get
            {
                var time = StartTimeTicks;

                if (time.HasValue)
                {
                    if (TimeSpan.FromTicks(time.Value).TotalSeconds - FastSeekOffsetSeconds > 0)
                    {
                        return string.Format(" -ss {0}", FastSeekOffsetSeconds);
                    }
                }

                return string.Empty;
            }
        }

        /// <summary>
        /// Gets the map args.
        /// </summary>
        /// <value>The map args.</value>
        protected virtual string MapArgs
        {
            get
            {
                var args = string.Empty;

                if (VideoStream != null)
                {
                    args += string.Format("-map 0:{0}", VideoStream.Index);
                }
                else
                {
                    args += "-map -0:v";
                }

                if (AudioStream != null)
                {
                    args += string.Format(" -map 0:{0}", AudioStream.Index);
                }
                else
                {
                    args += " -map -0:a";
                }

                if (SubtitleStream == null)
                {
                    args += " -map -0:s";
                }

                return args;
            }
        }

        /// <summary>
        /// The _library item
        /// </summary>
        private TBaseItemType _libraryItem;
        /// <summary>
        /// Gets the library item that will be played, if any
        /// </summary>
        /// <value>The library item.</value>
        protected TBaseItemType LibraryItem
        {
            get { return _libraryItem; }
        }

        /// <summary>
        /// Gets or sets the iso mount.
        /// </summary>
        /// <value>The iso mount.</value>
        private IIsoMount IsoMount { get; set; }

        /// <summary>
        /// The _audio stream
        /// </summary>
        private MediaStream _audioStream;
        /// <summary>
        /// Gets the audio stream.
        /// </summary>
        /// <value>The audio stream.</value>
        protected MediaStream AudioStream
        {
            get { return _audioStream ?? (_audioStream = GetMediaStream(AudioStreamIndex, MediaStreamType.Audio)); }
        }

        /// <summary>
        /// The _video stream
        /// </summary>
        private MediaStream _videoStream;
        /// <summary>
        /// Gets the video stream.
        /// </summary>
        /// <value>The video stream.</value>
        protected MediaStream VideoStream
        {
            get
            {
                // No video streams here
                // Need to make this check to make sure we don't pickup embedded image streams (which are listed in the file as type video)
                if (LibraryItem is Audio)
                {
                    return null;
                }

                return _videoStream ?? (_videoStream = GetMediaStream(VideoStreamIndex, MediaStreamType.Video));
            }
        }

        /// <summary>
        /// The subtitle stream
        /// </summary>
        private MediaStream _subtitleStream;
        /// <summary>
        /// Gets the subtitle stream.
        /// </summary>
        /// <value>The subtitle stream.</value>
        protected MediaStream SubtitleStream
        {
            get
            {
                // No subtitle streams here
                if (LibraryItem is Audio)
                {
                    return null;
                }

                return _subtitleStream ?? (_subtitleStream = GetMediaStream(SubtitleStreamIndex, MediaStreamType.Subtitle, false));
            }
        }

        /// <summary>
        /// Determines which stream will be used for playback
        /// </summary>
        /// <param name="desiredIndex">Index of the desired.</param>
        /// <param name="type">The type.</param>
        /// <param name="returnFirstIfNoIndex">if set to <c>true</c> [return first if no index].</param>
        /// <returns>MediaStream.</returns>
        private MediaStream GetMediaStream(int? desiredIndex, MediaStreamType type, bool returnFirstIfNoIndex = true)
        {
            var streams = LibraryItem.MediaStreams.Where(s => s.Type == type).ToList();

            if (desiredIndex.HasValue)
            {
                var stream = streams.FirstOrDefault(s => s.Index == desiredIndex.Value);

                if (stream != null)
                {
                    return stream;
                }
            }

            // Just return the first one
            return returnFirstIfNoIndex ? streams.FirstOrDefault() : null;
        }

        /// <summary>
        /// Gets the response info.
        /// </summary>
        /// <returns>Task{ResponseInfo}.</returns>
        protected override Task<ResponseInfo> GetResponseInfo()
        {
            var info = new ResponseInfo
            {
                ContentType = MimeTypes.GetMimeType(OutputFilePath),
                CompressResponse = false
            };

            return Task.FromResult(info);
        }

        /// <summary>
        /// Gets the client's desired audio bitrate
        /// </summary>
        /// <value>The audio bit rate.</value>
        protected int? AudioBitRate
        {
            get
            {
                var val = QueryString["AudioBitRate"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the client's desired video bitrate
        /// </summary>
        /// <value>The video bit rate.</value>
        protected int? VideoBitRate
        {
            get
            {
                var val = QueryString["VideoBitRate"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the desired audio stream index
        /// </summary>
        /// <value>The index of the audio stream.</value>
        private int? AudioStreamIndex
        {
            get
            {
                var val = QueryString["AudioStreamIndex"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the desired video stream index
        /// </summary>
        /// <value>The index of the video stream.</value>
        private int? VideoStreamIndex
        {
            get
            {
                var val = QueryString["VideoStreamIndex"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the desired subtitle stream index
        /// </summary>
        /// <value>The index of the subtitle stream.</value>
        private int? SubtitleStreamIndex
        {
            get
            {
                var val = QueryString["SubtitleStreamIndex"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the audio channels.
        /// </summary>
        /// <value>The audio channels.</value>
        public int? AudioChannels
        {
            get
            {
                var val = QueryString["audiochannels"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the audio sample rate.
        /// </summary>
        /// <value>The audio sample rate.</value>
        public int? AudioSampleRate
        {
            get
            {
                var val = QueryString["audiosamplerate"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// If we're going to put a fixed size on the command line, this will calculate it
        /// </summary>
        /// <param name="outputVideoCodec">The output video codec.</param>
        /// <returns>System.String.</returns>
        protected string GetOutputSizeParam(string outputVideoCodec)
        {
            // http://sonnati.wordpress.com/2012/10/19/ffmpeg-the-swiss-army-knife-of-internet-streaming-part-vi/

            var assSubtitleParam = string.Empty;

            if (SubtitleStream != null)
            {
                if (SubtitleStream.Codec.IndexOf("srt", StringComparison.OrdinalIgnoreCase) != -1 || SubtitleStream.Codec.IndexOf("subrip", StringComparison.OrdinalIgnoreCase) != -1)
                {
                    assSubtitleParam = GetTextSubtitleParam(SubtitleStream);
                }
            }

            // If fixed dimensions were supplied
            if (Width.HasValue && Height.HasValue)
            {
                return string.Format(" -vf \"scale={0}:{1}{2}\"", Width.Value, Height.Value, assSubtitleParam);
            }

            var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase);

            // If a fixed width was requested
            if (Width.HasValue)
            {
                return isH264Output ?
                    string.Format(" -vf \"scale={0}:trunc(ow/a/2)*2{1}\"", Width.Value, assSubtitleParam) :
                    string.Format(" -vf \"scale={0}:-1{1}\"", Width.Value, assSubtitleParam);
            }

            // If a max width was requested
            if (MaxWidth.HasValue && !MaxHeight.HasValue)
            {
                return isH264Output ?
                    string.Format(" -vf \"scale=min(iw\\,{0}):trunc(ow/a/2)*2{1}\"", MaxWidth.Value, assSubtitleParam) :
                    string.Format(" -vf \"scale=min(iw\\,{0}):-1{1}\"", MaxWidth.Value, assSubtitleParam);
            }

            // Need to perform calculations manually

            // Try to account for bad media info
            var currentHeight = VideoStream.Height ?? MaxHeight ?? Height ?? 0;
            var currentWidth = VideoStream.Width ?? MaxWidth ?? Width ?? 0;

            var outputSize = DrawingUtils.Resize(currentWidth, currentHeight, Width, Height, MaxWidth, MaxHeight);

            // If we're encoding with libx264, it can't handle odd numbered widths or heights, so we'll have to fix that
            if (isH264Output)
            {
                return string.Format(" -vf \"scale=trunc({0}/2)*2:trunc({1}/2)*2{2}\"", outputSize.Width, outputSize.Height, assSubtitleParam);
            }

            // Otherwise use -vf scale since ffmpeg will ensure internally that the aspect ratio is preserved
            return string.Format(" -vf \"scale={0}:-1{1}\"", Convert.ToInt32(outputSize.Width), assSubtitleParam);
        }

        /// <summary>
        /// Gets the text subtitle param.
        /// </summary>
        /// <param name="subtitleStream">The subtitle stream.</param>
        /// <returns>System.String.</returns>
        protected string GetTextSubtitleParam(MediaStream subtitleStream)
        {
            var path = subtitleStream.IsExternal ? GetConvertedAssPath(subtitleStream) : GetExtractedAssPath(subtitleStream);

            if (string.IsNullOrEmpty(path))
            {
                return string.Empty;
            }

            var param = string.Format(",ass={0}", path);

            var time = StartTimeTicks;

            if (time.HasValue)
            {
                var seconds = Convert.ToInt32(TimeSpan.FromTicks(time.Value).TotalSeconds);
                param += string.Format(",setpts=PTS-{0}/TB", seconds);
            }

            return param;
        }

        /// <summary>
        /// Gets the extracted ass path.
        /// </summary>
        /// <param name="subtitleStream">The subtitle stream.</param>
        /// <returns>System.String.</returns>
        private string GetExtractedAssPath(MediaStream subtitleStream)
        {
            var video = LibraryItem as Video;

            var path = Kernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");

            if (!File.Exists(path))
            {
                var success = Kernel.FFMpegManager.ExtractTextSubtitle(video, subtitleStream.Index, path, CancellationToken.None).Result;

                if (!success)
                {
                    return null;
                }
            }

            return path;
        }

        /// <summary>
        /// Gets the converted ass path.
        /// </summary>
        /// <param name="subtitleStream">The subtitle stream.</param>
        /// <returns>System.String.</returns>
        private string GetConvertedAssPath(MediaStream subtitleStream)
        {
            var video = LibraryItem as Video;

            var path = Kernel.FFMpegManager.GetSubtitleCachePath(video, subtitleStream.Index, ".ass");

            if (!File.Exists(path))
            {
                var success = Kernel.FFMpegManager.ConvertTextSubtitle(subtitleStream, path, CancellationToken.None).Result;

                if (!success)
                {
                    return null;
                }
            }

            return path;
        }

        /// <summary>
        /// Gets the internal graphical subtitle param.
        /// </summary>
        /// <param name="subtitleStream">The subtitle stream.</param>
        /// <param name="videoCodec">The video codec.</param>
        /// <returns>System.String.</returns>
        protected string GetInternalGraphicalSubtitleParam(MediaStream subtitleStream, string videoCodec)
        {
            var outputSizeParam = string.Empty;

            // Add resolution params, if specified
            if (Width.HasValue || Height.HasValue || MaxHeight.HasValue || MaxWidth.HasValue)
            {
                outputSizeParam = GetOutputSizeParam(videoCodec).TrimEnd('"');
                outputSizeParam = "," + outputSizeParam.Substring(outputSizeParam.IndexOf("scale", StringComparison.OrdinalIgnoreCase));
            }

            return string.Format(" -filter_complex \"[0:{0}]format=yuva444p,lut=u=128:v=128:y=gammaval(.3)[sub] ; [0:0] [sub] overlay{1}\"", subtitleStream.Index, outputSizeParam);
        }

        /// <summary>
        /// Gets the fixed output video height, in pixels
        /// </summary>
        /// <value>The height.</value>
        protected 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>
        /// <value>The width.</value>
        protected 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>
        /// <value>The height of the max.</value>
        protected 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>
        /// <value>The width of the max.</value>
        protected int? MaxWidth
        {
            get
            {
                string val = QueryString["maxwidth"];

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

                return int.Parse(val);
            }
        }

        /// <summary>
        /// Gets the output video framerate
        /// </summary>
        /// <value>The max frame rate.</value>
        protected float? FrameRate
        {
            get
            {
                string val = QueryString["framerate"];

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

                return float.Parse(val);
            }
        }

        /// <summary>
        /// Gets the number of audio channels to specify on the command line
        /// </summary>
        /// <returns>System.Nullable{System.Int32}.</returns>
        protected int? GetSampleRateParam()
        {
            // If the user requested a max value
            if (AudioSampleRate.HasValue)
            {
                return AudioSampleRate.Value;
            }

            return null;
        }

        /// <summary>
        /// Gets the number of audio channels to specify on the command line
        /// </summary>
        /// <param name="audioCodec">The audio codec.</param>
        /// <returns>System.Nullable{System.Int32}.</returns>
        protected int? GetNumAudioChannelsParam(string audioCodec)
        {
            if (AudioStream.Channels > 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();
        }

        /// <summary>
        /// Gets the number of audio channels to specify on the command line
        /// </summary>
        /// <returns>System.Nullable{System.Int32}.</returns>
        protected int? GetNumAudioChannelsParam()
        {
            // If the user requested a max number of channels
            if (AudioChannels.HasValue)
            {
                return AudioChannels.Value;
            }

            return null;
        }

        /// <summary>
        /// Determines whether the specified stream is H264.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns><c>true</c> if the specified stream is H264; otherwise, <c>false</c>.</returns>
        protected bool IsH264(MediaStream stream)
        {
            return stream.Codec.IndexOf("264", StringComparison.OrdinalIgnoreCase) != -1 ||
                   stream.Codec.IndexOf("avc", StringComparison.OrdinalIgnoreCase) != -1;
        }

        /// <summary>
        /// Gets the name of the output audio codec
        /// </summary>
        /// <returns>System.String.</returns>
        protected string GetAudioCodec()
        {
            if (AudioCodec.HasValue)
            {
                if (AudioCodec == AudioCodecs.Aac)
                {
                    return "libvo_aacenc";
                }
                if (AudioCodec == AudioCodecs.Mp3)
                {
                    return "libmp3lame";
                }
                if (AudioCodec == AudioCodecs.Vorbis)
                {
                    return "libvorbis";
                }
                if (AudioCodec == AudioCodecs.Wma)
                {
                    return "wmav2";
                }
            }

            return "copy";
        }

        /// <summary>
        /// Gets the name of the output video codec
        /// </summary>
        /// <returns>System.String.</returns>
        protected string GetVideoCodec()
        {
            if (VideoCodec.HasValue)
            {
                if (VideoCodec == VideoCodecs.H264)
                {
                    return "libx264";
                }
                if (VideoCodec == VideoCodecs.Vpx)
                {
                    return "libvpx";
                }
                if (VideoCodec == VideoCodecs.Wmv)
                {
                    return "wmv2";
                }
                if (VideoCodec == VideoCodecs.Theora)
                {
                    return "libtheora";
                }
            }

            return "copy";
        }

        /// <summary>
        /// Gets the input argument.
        /// </summary>
        /// <param name="isoMount">The iso mount.</param>
        /// <returns>System.String.</returns>
        protected string GetInputArgument(IIsoMount isoMount)
        {
            return isoMount == null ?
                Kernel.FFMpegManager.GetInputArgument(LibraryItem) :
                Kernel.FFMpegManager.GetInputArgument(LibraryItem as Video, IsoMount);
        }

        /// <summary>
        /// Starts the FFMPEG.
        /// </summary>
        /// <param name="outputPath">The output path.</param>
        /// <returns>Task.</returns>
        protected async Task StartFFMpeg(string outputPath)
        {
            var video = LibraryItem as Video;

            //if (video != null && video.VideoType == VideoType.Iso &&
            //    video.IsoType.HasValue && Kernel.IsoManager.CanMount(video.Path))
            //{
            //    IsoMount = await Kernel.IsoManager.Mount(video.Path, CancellationToken.None).ConfigureAwait(false);
            //}

            var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,

                    // Must consume both stdout and stderr or deadlocks may occur
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,

                    FileName = Kernel.FFMpegManager.FFMpegPath,
                    WorkingDirectory = Path.GetDirectoryName(Kernel.FFMpegManager.FFMpegPath),
                    Arguments = GetCommandLineArguments(outputPath, IsoMount),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            Plugin.Instance.OnTranscodeBeginning(outputPath, TranscodingJobType, process);

            //Logger.Info(process.StartInfo.FileName + " " + process.StartInfo.Arguments);

            var logFilePath = Path.Combine(Kernel.ApplicationPaths.LogDirectoryPath, "ffmpeg-" + Guid.NewGuid() + ".txt");

            // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
            LogFileStream = new FileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous);

            process.Exited += OnFFMpegProcessExited;

            try
            {
                process.Start();
            }
            catch (Win32Exception ex)
            {
                //Logger.ErrorException("Error starting ffmpeg", ex);

                Plugin.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType);

                process.Exited -= OnFFMpegProcessExited;
                LogFileStream.Dispose();

                throw;
            }

            // MUST read both stdout and stderr asynchronously or a deadlock may occurr
            process.BeginOutputReadLine();

            // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
            process.StandardError.BaseStream.CopyToAsync(LogFileStream);

            // Wait for the file to exist before proceeeding
            while (!File.Exists(outputPath))
            {
                await Task.Delay(100).ConfigureAwait(false);
            }
        }

        /// <summary>
        /// Processes the exited.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void OnFFMpegProcessExited(object sender, EventArgs e)
        {
            if (IsoMount != null)
            {
                IsoMount.Dispose();
                IsoMount = null;
            }

            var outputFilePath = OutputFilePath;

            LogFileStream.Dispose();

            var process = (Process)sender;

            process.Exited -= OnFFMpegProcessExited;

            int? exitCode = null;

            try
            {
                exitCode = process.ExitCode;
                //Logger.Info("FFMpeg exited with code {0} for {1}", exitCode.Value, outputFilePath);
            }
            catch
            {
                //Logger.Info("FFMpeg exited with an error for {0}", outputFilePath);
            }

            process.Dispose();

            Plugin.Instance.OnTranscodingFinished(outputFilePath, TranscodingJobType);

            if (!exitCode.HasValue || exitCode.Value != 0)
            {
                //Logger.Info("Deleting partial stream file(s) {0}", outputFilePath);

                try
                {
                    DeletePartialStreamFiles(outputFilePath);
                }
                catch (IOException ex)
                {
                    //Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, outputFilePath);
                }
            }
            else
            {
                //Logger.Info("FFMpeg completed and exited normally for {0}", outputFilePath);
            }
        }

        /// <summary>
        /// Deletes the partial stream files.
        /// </summary>
        /// <param name="outputFilePath">The output file path.</param>
        protected abstract void DeletePartialStreamFiles(string outputFilePath);
    }
}