Ejemplo n.º 1
0
 public TV(string manufacturer, string model, decimal price, uint count, string boxingColor, VideoFormat[] formats, Display display)
     : base(manufacturer,  model,  price,  count)
 {
     this.boxingColor = boxingColor;
     this.formats = formats;
     this.display = display;
 }
Ejemplo n.º 2
0
 public Monitor(string manufacturer, string model, decimal price, uint count, bool hasTuner, VideoFormat[] formats, Display display)
     : base(manufacturer, model, price, count)
 {
     this.hasTuner = hasTuner;
     this.formats = formats;
     this.display = display;
 }
Ejemplo n.º 3
0
        //Manually specify output directory
        public void BeginConversion(string vidPath, string outputDirectory, VideoFormat vidFormat)
        {
            if (_vidWorker.IsBusy)
            {
                MessageBox.Show("Please wait for the current conversion to finish", "Conversion in Progress",
                   MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);

            }
            else if (!File.Exists(vidPath))
            {
                MessageBox.Show("Please specify a valid video file", "File Not Found",
                   MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
            }
            else if (!Directory.Exists(outputDirectory))
            {
                MessageBox.Show("The output directory you selected can't be found", "No Output Directory",
                  MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
            }
            else
            {
                _outputDirectory = outputDirectory;
                _vidPath = vidPath;
                _vidFormat = vidFormat;
                //Creates a temporary copy of the specified video file in the program's directory, overwritting files with the same name
                _tempVidPath = _tempDirectory + "\\" + "Temp_Copy_" + Path.GetFileName(vidPath);
                File.Copy(vidPath, _tempVidPath, true);

                _vidWorker.RunWorkerAsync();
            }
        }
Ejemplo n.º 4
0
 public DvdPlayer(string manufacturer, string model, decimal price, uint count, Dimensions dimentions, VideoFormat[] formats, Display display)
     : base(manufacturer, model, price, count)
 {
     this.dimentions = dimentions;
     this.formats = formats;
     this.display = display;
 }
Ejemplo n.º 5
0
 protected override void OnFormatChange(VideoFormat videoFormat)
 {
     if (CapturedFormat != null)
     {
         throw new InvalidOperationException("Can't cope with change!");
     }
     CapturedFormat = videoFormat;
 }
Ejemplo n.º 6
0
 public Disk(string name, string path, VideoFormat format, string extraOptions)
     : this()
 {
     this.Name = name;
     this.Path = path;
     this.Format = format;
     this.ExtraOptions = string.IsNullOrEmpty(extraOptions) ? null : extraOptions;
 }
Ejemplo n.º 7
0
 public void CalculateIwtSizes(VideoFormat format)
 {
     int[] size = new int[]{0,0};
     format.GetPictureLumaSize(ref size);
     iwtLumaSize = new Dimension(Util.RoundUpPow2(size[0], transformDepth),
                     Util.RoundUpPow2(size[1], transformDepth));
     format.GetPictureChromaSize(ref size);
     iwtChromaSize = new Dimension(Util.RoundUpPow2(size[0], transformDepth),
                       Util.RoundUpPow2(size[1], transformDepth));
 }
Ejemplo n.º 8
0
      /// <summary>
      /// Invoked when a video device reports a  video format change.
      /// </summary>
      /// <param name="videoFormat">The new video format.</param>
      protected override void OnFormatChange(VideoFormat videoFormat)
      {
         if (videoFormat.PixelFormat != PixelFormatType.Format32bppArgb)
         {
            throw new InvalidOperationException(String.Format("Only 32 Bit ARGB pixel format is supported, not {0}.", videoFormat.PixelFormat));
         }

         detector.ChangeFormat(videoFormat.PixelWidth, videoFormat.PixelHeight);
         vidFormat = videoFormat;
      }
 public ITranscode GetTranscoder(TranscodeInfo info, VideoFormat format)
 {
   string ext = System.IO.Path.GetExtension(info.file).ToLower();
   if (ext == ".dvr-ms") return new Dvrms2Mpeg();
   else
   {
     if (format == VideoFormat.Wmv)
       return new DVRMS2WMV();
   }
   return null;
 }
Ejemplo n.º 10
0
        public void Reset(VideoFormat? videoFormat)
        {
            m_PrevFrameNo = -1;
            m_PrevOddTicks = -1;
            m_PrevEvenTicks = -1;
            m_PrevOddFieldNo = -1;
            m_PrevEvenFieldNo = -1;

            if (!videoFormat.HasValue)
                throw new ArgumentException();

            m_VideoFormat = videoFormat.Value;
        }
Ejemplo n.º 11
0
 internal Converting(string fileName, VideoFormat format)
 {
     InitializeComponent();
     this.ffmpegOutput = new List<string>();
     fileNameLabel.Content = IOPath.GetFileName(fileName);
     progressLabel.Content = "Starting...";
     converter = format.MakeConverter(fileName);
     converter.Output += new EventHandler<ProcessOutputArgs>(converter_FFMPEGOutput);
     converter.ConvertProgress +=
         new EventHandler<VideoConvertProgressArgs>(converter_ConvertProgress);
     converter.Finished += new EventHandler<EventArgs>(converter_Finished);
     converter.UnknownFormat += new EventHandler<EventArgs>(converter_UnknownFormat);
     converter.Start();
 }
Ejemplo n.º 12
0
 public HomeTheatre(string manafacturer, string model, decimal price, uint count,
     Frequency frequencyRange, int power, VideoFormat[] formats, Display display,
     Amplifier amplifier, Speakers[] speakers, TV tv, DvdPlayer dvdPlayer)
     : base(manafacturer, model, price, count)
 {
     this.FrequencyRange = frequencyRange;
     this.Power = power;
     this.Formats = formats;
     this.Display = display;
     this.Amplifier = amplifier;
     this.Speakers = speakers;
     this.TV = tv;
     this.DVDPlayer = dvdPlayer;
 }
Ejemplo n.º 13
0
 public void Render(Block[] outBlocks, VideoFormat f)
 {
     for(int k = 0; k < outBlocks.Length; k++) {
         InitializeRender(k,f);
         block = new Block(new Dimension(xblen, yblen));
         for(int i = 0; i < par.num_refs; i++)
         tmp_ref[i] = refs[i][k];
         for(int j = 0; j < par.y_num_blocks; j++)
         for(int i = 0; i < par.x_num_blocks; i++) {
             PredictBlock(outBlocks[k], i, j, k);
             AccumulateBlock(outBlocks[k], i*xbsep - xoffset,
                     j*ybsep - yoffset);
         }
         outBlocks[k].ShiftOut(6,0);
         outBlocks[k].Clip(7);
     }
 }
Ejemplo n.º 14
0
        public static void Convert(string fileName, VideoFormat fmt)
        {
            if (fmt == VideoFormat.None) throw new ArgumentException("Invalid argmument.", "fmt");

            string cmd = String.Empty;

            if (fmt == VideoFormat.AVI) cmd = ToAVICmdLine;
            if (fmt == VideoFormat.MPEG) cmd = ToMPEGCmdLine;
            if (fmt == VideoFormat.MP3) cmd = ToMP3CmdLine;

            string directory = Path.GetDirectoryName(fileName);

            // the original file name ends with 'AVI', 'MPEG', 'MP3'....new we rename the file to .FLV

            string flvPath = Path.Combine(directory, String.Concat(Guid.NewGuid().ToString("N"), ".flv"));

            try
            {
                File.Move(fileName, flvPath);

                string sourceFile = Path.GetFileName(flvPath);
                string targetFile = Path.GetFileName(fileName);

                cmd = String.Format(cmd, sourceFile, targetFile);

                string toolPath = Path.GetDirectoryName(Application.ExecutablePath);
                //toolPath = @"C:\Documents and Settings\guilherme.labigalini\Desktop\MyDownloader\MyDownloader\MyDownloader.App\bin\Debug\";
                ProcessStartInfo psi = new ProcessStartInfo(toolPath + "\\" + ffmpeg, cmd);
                psi.UseShellExecute = false;
                psi.CreateNoWindow = true;
                psi.WorkingDirectory = directory;

                using (Process p = Process.Start(psi))
                {
                    p.WaitForExit();
                }
            }
            finally
            {
                File.Delete(flvPath);
            }
        }
        /// <summary>
        /// Callback from the media platform when raw video is received. This is loopbacked to the user after adding the hue of the user's choice
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnVideoMediaReceived(object sender, VideoMediaReceivedEventArgs e)
        {
            try
            {
                CorrelationId.SetCurrentId(_correlationId);

                Log.Verbose(
                    new CallerInfo(),
                    LogContext.Media,
                    "[{0}] [VideoMediaReceivedEventArgs(Data=<{1}>, Length={2}, Timestamp={3}, Width={4}, Height={5}, ColorFormat={6}, FrameRate={7})]",
                    this.Id,
                    e.Buffer.Data.ToString(),
                    e.Buffer.Length,
                    e.Buffer.Timestamp,
                    e.Buffer.VideoFormat.Width,
                    e.Buffer.VideoFormat.Height,
                    e.Buffer.VideoFormat.VideoColorFormat,
                    e.Buffer.VideoFormat.FrameRate);


                byte[] buffer = new byte[e.Buffer.Length];
                Marshal.Copy(e.Buffer.Data, buffer, 0, (int)e.Buffer.Length);

                VideoMediaBuffer videoRenderMediaBuffer = e.Buffer as VideoMediaBuffer;
                AddHue(DefaultHueColor, buffer, e.Buffer.VideoFormat.Width, e.Buffer.VideoFormat.Height);

                VideoFormat sendVideoFormat = GetSendVideoFormat(e.Buffer.VideoFormat);
                var         videoSendBuffer = new VideoSendBuffer(buffer, (uint)buffer.Length, sendVideoFormat);
                _videoSocket.Send(videoSendBuffer);
            }
            catch (Exception ex)
            {
                Log.Error(new CallerInfo(), LogContext.Media, $"[{this.Id}]: Exception in VideoMediaReceived {ex.ToString()}");
            }
            finally
            {
                e.Buffer.Dispose();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets a value indicating whether the supplied path validates as a video file
        /// </summary>
        /// <param name="path">filepath to validate</param>
        /// <returns>True if the file validates as a video file</returns>
        public static bool IsVideoFile(string path)
        {
            try {
                VideoFormat format = GetVideoFormat(path);
                if (format == VideoFormat.NotSupported)
                {
                    return(false);
                }

                // image files are only valid if DaemonTools is enabled
                if (format == VideoFormat.Unknown && !MediaPortal.Util.DaemonTools.IsEnabled)
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception e) {
                logger.Error("Error in video file scan for \"{0}\": {1}", path, e.Message);
                return(false);
            }
        }
Ejemplo n.º 17
0
        public int Load(byte[] buffer, int startIndex, int bufferLength)
        {
            // If less than 14 bytes are available for processing then the header and following start code
            // can't be read.
            if ((bufferLength - startIndex) < 14)
            {
                return(0);
            }

            int index = startIndex;

            extensionStartCodeIdentifier = buffer[index + 4] >> 4;
            videoFormat       = (VideoFormat)((buffer[index + 4] & 0xE) >> 1);
            colourDescription = buffer[index + 4] & 0x01;

            index += 5;
            if (colourDescription == 1)
            {
                colourPrimaries         = (ColourPrimaries)(buffer[index++]);
                transferCharacteristics = (TransferCharacteristics)(buffer[index++]);
                matrixCoefficients      = (MatrixCoefficients)(buffer[index++]);
            }

            displayHorizontalSize = Read16(buffer, index++) >> 2;
            displayVerticalSize   = (Read16(buffer, index += 2) & 0x1FFE) >> 1;

            while (index < (bufferLength - 4))
            {
                if ((Read32(buffer, index) >> 8) == 1)
                {
                    return(index - startIndex);
                }

                index++;
            }

            return(0);
        }
Ejemplo n.º 18
0
        public void OnClientVideoReceived(I420AVideoFrame frame)
        {
            if (DateTime.Now > this.lastVideoSentToClientTimeUtc + TimeSpan.FromMilliseconds(33))
            {
                try
                {
                    this.lastVideoSentToClientTimeUtc = DateTime.Now;

                    byte[] i420Frame = new byte[frame.width * frame.height * 12 / 8];
                    frame.CopyTo(i420Frame);

                    byte[] nv12Frame = VideoConverter.I420ToNV12(i420Frame);

                    VideoFormat sendVideoFormat = VideoFormatUtil.GetSendVideoFormat((int)frame.height, (int)frame.width);
                    var         videoSendBuffer = new VideoSendBuffer(nv12Frame, (uint)nv12Frame.Length, sendVideoFormat);
                    this.Call.GetLocalMediaSession().VideoSocket.Send(videoSendBuffer);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
Ejemplo n.º 19
0
        protected override Matroska.VideoSink CreateVideoSink()
        {
            var fileIndex                = 0;
            var fileExtension            = "mkv";
            var filePathWithoutExtension = ProcessFilePath(Path.Combine(Options.OutputPath, Options.OutputFileName), RemoteConnectionInfo);
            var filePath = $"{filePathWithoutExtension}-{fileIndex}.{fileExtension}";

            while (File.Exists(filePath))
            {
                filePath = $"{filePathWithoutExtension}-{++fileIndex}.{fileExtension}";
            }

            //TODO: should the JSON here follow the media server conventions?
            var jsonPath = filePath + ".json";

            File.WriteAllText(jsonPath, RemoteConnectionInfo.ToJson());
            Console.WriteLine(jsonPath);

            var format = VideoFormat.Clone();

            format.IsPacketized = false;
            return(new Matroska.VideoSink(filePath, format));
        }
Ejemplo n.º 20
0
        private string createDefaultArguments(VideoFormat videoFormat, string inputFilePath, string outputFilePath, DicomElement dicomElement)
        {
            // for ffmpeg testing
            //ffmpeg -i test-video.avi -r 2 -qscale 31 -f m4v m5.mpg
            // mpeg1 supports only specific fps values, see mpeg12data.c from ffmpeg source
            string format = videoFormat.ToString().ToLower();

            int    originalFps;
            string strOriginalFps = dicomElement.DicomFile.DataSet[DicomTags.CineRate].GetString(0, "");

            if (int.TryParse(strOriginalFps, out originalFps) == false)
            {
                originalFps = Settings.Default.Fps;
            }

            int fps = (videoFormat == VideoFormat.MPEG) ? 24 : originalFps;

            return(@"-i " + inputFilePath
                   + " -r " + fps
                   + " -qscale " + Settings.Default.Quality
                   + " -f " + format
                   + " \"" + outputFilePath + "\"");
        }
Ejemplo n.º 21
0
        public bool IsDefined(VideoFormat fmt)
        {
            switch (fmt)
            {
            case VideoFormat.Fmt3DSBS:

                return(SelectedDeviceModel.RemoteCommandSequences.Commands2D3DSBS.Count > 0);

            case VideoFormat.Fmt3DTAB:

                return(SelectedDeviceModel.RemoteCommandSequences.Commands2D3DTAB.Count > 0);

            case VideoFormat.Fmt2D3D:

                return(SelectedDeviceModel.RemoteCommandSequences.Commands2D3D.Count > 0);

            case VideoFormat.Mvc3D:

                return(SelectedDeviceModel.RemoteCommandSequences.Commands3DMVC.Count > 0);
            }

            return(false);
        }
Ejemplo n.º 22
0
        private void doCompression(VideoFormat videoFormat, string tmpAviFilePath, DicomElement dicomElement)
        {
            string format           = videoFormat.ToString().ToLower();
            string outputFileName   = Path.GetFileNameWithoutExtension(dicomElement.FilePath) + "." + format;
            string outputFolderPath = Settings.Default.ExportPath + dicomElement.GetSubFolderPath(format);

            Directory.CreateDirectory(outputFolderPath);
            string outputFilePath = Path.Combine(outputFolderPath, outputFileName);

            if (File.Exists(outputFilePath))
            {
                outputFilePath = renameToNonExistentFileName(outputFilePath);
            }

            if (videoFormat == VideoFormat.M4V)
            {
                executeMultiPassesCommandsForM4v(tmpAviFilePath, outputFilePath);
            }
            else
            {
                executeFFmpegCommand(createDefaultArguments(videoFormat, tmpAviFilePath, outputFilePath, dicomElement));
            }
        }
        public VideoConvertSettings(VideoQuality quality, int frameRate, VideoFormat format)
        {
            FrameRate = frameRate;
            Format    = format;

            switch (quality)
            {
            case VideoQuality.Vq240P:
                FrameHeight = 240;
                break;

            case VideoQuality.Vq360P:
                FrameHeight = 360;
                break;

            case VideoQuality.Vq480P:
                FrameHeight = 480;
                break;

            case VideoQuality.Vq720P:
                FrameHeight = 720;
                break;
            }
        }
Ejemplo n.º 24
0
        public string MergeAudioSegments(List <string> audioFiles, VideoFormat type)
        {
            string        tempFile = Path.GetTempPath() + Guid.NewGuid() + "." + type.ToString();
            List <string> files    = audioFiles;

            string outputOptions = string.Empty;

            string copyAll = " -c:v copy -c:a copy";

            for (int i = 0; i < files.Count; i++)
            {
                outputOptions += "-map " + (i + 1) + ":0";
                if (i + files.Count < files.Count)
                {
                    outputOptions += " ";
                }
            }

            FFMPEGParameters parameters = new FFMPEGParameters()
            {
                InputFilePath        = FilePath,
                DisableAudio         = false,
                AdditionalFileInputs = files,
                OutputOptions        = outputOptions + copyAll,
                OutputFilePath       = tempFile,
            };

            string output = FFMpegService.Execute(parameters);

            if (!File.Exists(tempFile))
            {
                throw new Exception("Could not create single frame image from video clip");
            }

            return(tempFile);
        }
Ejemplo n.º 25
0
        private async Task <DownloadItem> ParseVideoInfo(string parseUrl, VideoFormat outputFormat)
        {
            string cmd = BuildVideoMetaDataCmd(parseUrl);

            var msg = await ProcessHelper.Run(ConfigHelper.VideoResolveTool, cmd, TimeSpan.FromMilliseconds(10000));

            List <string> infoList = msg.Item1.Split('\n').ToList();

            //获取视频下载地址
            Uri                 uriResult;
            List <string>       videoUrlList  = infoList.Where(info => Uri.TryCreate(info, UriKind.Absolute, out uriResult)).ToList();
            List <DownloadPart> videoPartList = new List <DownloadPart>();

            foreach (var url in videoUrlList)
            {
                var part = new DownloadPart();
                part.Url       = url;
                part.StorePath = FileHelper.GenerateRandomFilePath(VideoFormat.FLV.GetDescription());

                videoPartList.Add(part);
            }

            //获取视频名称
            string title = infoList.Except(videoUrlList).First();

            DownloadItem item = new DownloadItem();

            item.Title        = title;
            item.PartList     = videoPartList;
            item.Status       = DownloadStatus.New;
            item.StorePath    = Path.Combine(ConfigHelper.DownloadDir, title + outputFormat.GetDescription());
            item.OutputFormat = outputFormat;
            item.Url          = parseUrl;

            return(item);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Returns the video format of the media given the path
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static VideoFormat GetVideoFormatFromPath(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return(VideoFormat.UNKNOWN);
            }

            switch (GetDirectoryMediaType(path))
            {
            case DirectoryType.DVD:
                return(VideoFormat.DVD);

            case DirectoryType.BluRay:
                return(VideoFormat.BLURAY);

            case DirectoryType.HDDVD:
                return(VideoFormat.HDDVD);
            }

            VideoFormat returnFormat = VideoFormat.UNKNOWN;

            string extension = Path.GetExtension(path);

            if (string.IsNullOrEmpty(extension))
            {
                return(VideoFormat.UNKNOWN);
            }

            try
            {
                returnFormat = (VideoFormat)Enum.Parse(typeof(VideoFormat), extension.Replace(".", string.Empty), true);
            }
            catch (ArgumentException) { }

            return(returnFormat);
        }
Ejemplo n.º 27
0
 public async Task<Result<YoutubeDownloadResult, string>> DownloadYoutubeVideo(VideoFormat video)
 {
     return await DownloadYoutubeVideo(video as YTEVideoFormat);
 }
Ejemplo n.º 28
0
        public void ManualSelect3DFormat(VideoFormat preSelected)
        {
            _dlgMenu = (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);

            if (_dlgMenu != null)
            {
                _dlgMenu.Reset();
                _dlgMenu.SetHeading("Select 2D/3D Format for TV");

                if (preSelected == VideoFormat.Fmt2D)
                {
                    _dlgMenu.Add("2D");
                }

                if (preSelected == VideoFormat.Fmt2D || preSelected == VideoFormat.Fmt3DSBS)
                {
                    _dlgMenu.Add("3D Side by Side");
                    _dlgMenu.Add("3D SBS -> 2D via MediaPortal");
                }

                if (preSelected == VideoFormat.Fmt2D || preSelected == VideoFormat.Fmt3DTAB)
                {
                    _dlgMenu.Add("3D Top and Bottom");
                    _dlgMenu.Add("3D TAB -> 2D via MediaPortal");
                }

                if (bConvert2Dto3DEnabled && preSelected == VideoFormat.Fmt2D)
                {
                    _dlgMenu.Add("2D -> 3D SBS via MediaPortal");
                }

                if (_currentMode == VideoFormat.Fmt3DSBS || _currentMode == VideoFormat.Fmt3DTAB)
                {
                    if (!GUIGraphicsContext.Switch3DSides)
                    {
                        _dlgMenu.Add("3D Reverse Mode");
                    }
                    else
                    {
                        _dlgMenu.Add("3D Normal Mode");
                    }
                }

                if (_activeDevice.IsDefined(VideoFormat.Fmt2D3D))
                {
                    _dlgMenu.Add("2D -> 3D via TV");
                }

                _dlgMenu.DoModal((int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO);

                Log.Info("Auto3D: Manually selected " + _dlgMenu.SelectedLabelText);

                switch (_dlgMenu.SelectedLabelText)
                {
                case "2D":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt2D);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.None;
                    _currentMode = VideoFormat.Fmt2D;
                    break;

                case "3D Side by Side":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt3DSBS);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.SideBySide;
                    _currentMode = VideoFormat.Fmt3DSBS;
                    break;

                case "3D Top and Bottom":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt3DTAB);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.TopAndBottom;
                    _currentMode = VideoFormat.Fmt3DTAB;
                    break;

                case "2D -> 3D via TV":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt2D3D);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.None;
                    _currentMode = VideoFormat.Fmt2D3D;
                    break;

                case "3D SBS -> 2D via MediaPortal":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt2D);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.SideBySideTo2D;
                    _currentMode = VideoFormat.Fmt2D;
                    break;

                case "3D TAB -> 2D via MediaPortal":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt2D);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.TopAndBottomTo2D;
                    _currentMode = VideoFormat.Fmt2D;
                    break;

                case "3D Reverse Mode":

                    GUIGraphicsContext.Switch3DSides = true;
                    break;

                case "3D Normal Mode":

                    GUIGraphicsContext.Switch3DSides = false;
                    break;

                case "2D -> 3D SBS via MediaPortal":

                    _activeDevice.SwitchFormat(_currentMode, VideoFormat.Fmt3DSBS);
                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.SideBySideFrom2D;
                    _currentMode = VideoFormat.Fmt3DSBS;
                    break;
                }

                _dlgMenu = null;
            }
        }
Ejemplo n.º 29
0
        unsafe static void Main(string[] args)
        {
            const double MinimumFrequency = 10;
            const double MaximumFrequency = 20000;
            const double MaxDB            = 65;
            const int    fftSize          = 4192 * 6;

            var reader      = new MediaReader(@"D:\CloudMusic\MAN WITH A MISSION - My Hero.mp3");
            var decoder     = reader.Decoders.OfType <AudioDecoder>().First();
            var videoFormat = new VideoFormat(1280, 720, AVPixelFormat.Rgb0);
            var writer      = new MediaWriter(@"D:\CloudMusic\MAN WITH A MISSION - My Hero-fft.mkv")
                              .AddEncoder(new VideoEncoder(AVCodecID.H264, videoFormat, new VideoEncoderParameters {
                FrameRate = new Fraction(30), GopSize = 10
            }))
                              .AddEncoder(new AudioEncoder(AVCodecID.Mp3, decoder.InFormat))
                              //.AddVideo(videoFormat, new VideoEncoderParameters { FrameRate = new Fraction(30), GopSize = 10 })
                              //.AddAudio(decoder.InFormat)
                              .Initialize();

            int sampleRate = decoder.InFormat.SampleRate;
            int channels   = decoder.InFormat.Channels;
            var resampler  = new AudioResampler(decoder.InFormat, new AudioFormat(sampleRate, channels, 64));
            var inFrame    = new AudioFrame();
            var outFrame   = new AudioFrame();
            var image      = new VideoFrame(videoFormat);

            var viewHeight  = videoFormat.Height / 2;
            var observer    = new StreamObserver <double>(fftSize * 2, fftSize / 6, 2);
            var fft         = DoubleFFT.Create(fftSize);
            var inFFT       = fft.AllocInput();
            var outFFT      = fft.AllocOutput();
            var cutLength   = FFTTools.CutFrequencyLength(fftSize, MinimumFrequency, MaximumFrequency, sampleRate, fft.FFTComplexCount);
            var cutFFT      = Marshal.AllocHGlobal(cutLength * sizeof(double));
            var outFFT2     = Marshal.AllocHGlobal(fft.FFTComplexCount * sizeof(double));
            var outFFTFinal = Marshal.AllocHGlobal(viewHeight * sizeof(double));
            var window      = new BlackmanHarrisWindow(fftSize);
            var log         = new Spectrum3DLog();

            void FFT()
            {
                window.Apply((double *)inFFT, (double *)inFFT);
                fft.Execute(inFFT, outFFT);
                FFTTools.Abs(fftSize, (double *)outFFT, (double *)outFFT2);
                FFTTools.CutFrequency(fftSize, (double *)outFFT2, fft.FFTComplexCount, MinimumFrequency, MaximumFrequency, sampleRate, (double *)cutFFT, cutLength);
                FFTTools.Logarithm((double *)cutFFT, cutLength, MinimumFrequency, MaximumFrequency, (double *)outFFTFinal, viewHeight, log);
                FFTTools.ToDB((double *)outFFTFinal, viewHeight, MaxDB);
                FFTTools.Scale((double *)outFFTFinal, viewHeight, 1 / MaxDB);
            }

            void LeftShiftImage()
            {
                int w = image.Format.Width - 1;
                int h = image.Format.Height;

                for (int y = 0; y < h; y++)
                {
                    var p = (uint *)(image.Data[0] + image.Format.Strides[0] * y);
                    for (int x = 0; x < w; x++)
                    {
                        p[x] = p[x + 1];
                    }
                }
            }

            observer.Completed += data => {
                LeftShiftImage();

                int w      = image.Format.Width - 1;
                int h      = image.Format.Height;
                var p      = (byte *)((uint *)image.Data[0] + w);
                var stride = image.Format.Strides[0];

                for (int i = 0; i < fftSize; i++)
                {
                    ((double *)inFFT)[i] = ((double *)data)[2 * i];
                }
                FFT();
                for (int y = 0; y < viewHeight; y++, p += stride)
                {
                    var val = ((double *)outFFTFinal)[viewHeight - y - 1] * 256;
                    if (val < 0)
                    {
                        val = 0;
                    }
                    else if (val > 255)
                    {
                        val = 255;
                    }
                    p[0] = p[1] = p[2] = (byte)val;
                }

                for (int i = 0; i < fftSize; i++)
                {
                    ((double *)inFFT)[i] = ((double *)data)[2 * i + 1];
                }
                FFT();
                for (int y = 0; y < viewHeight; y++, p += stride)
                {
                    var val = ((double *)outFFTFinal)[viewHeight - y - 1] * 256;
                    if (val < 0)
                    {
                        val = 0;
                    }
                    else if (val > 255)
                    {
                        val = 255;
                    }
                    p[0] = p[1] = p[2] = (byte)val;
                }
            };

            bool end = false, run = true;

            while (run)
            {
                writer.Write(encoder => {
                    switch (encoder)
                    {
                    case AudioEncoder audioEncoder:
                        Console.Write($"\r{audioEncoder.InputTimestamp}");
                        if (reader.NextFrame(inFrame, decoder.StreamIndex))
                        {
                            resampler.Resample(inFrame, outFrame);
                            observer.Write(outFrame.Data[0], outFrame.SampleCount * channels);
                            return(inFrame);
                        }
                        else
                        {
                            resampler.ResampleFinal(outFrame);
                            observer.Write(outFrame.Data[0], outFrame.SampleCount * channels);
                            end = true;
                            Console.WriteLine($"\r{audioEncoder.InputTimestamp}");
                            return(null);
                        }

                    case VideoEncoder videoEncoder:
                        if (end)
                        {
                            run = false;
                        }
                        return(image);

                    default:
                        throw new NotImplementedException();
                    }
                });
            }
            writer.Dispose();
        }
Ejemplo n.º 30
0
        // start playback of a file (using known format)
        private void playFile(string media, VideoFormat videoFormat)
        {
            logger.Debug("Processing media for playback: File={0}, VideoFormat={1}", media, videoFormat);

            // HD Playback
            if (videoFormat == VideoFormat.Bluray || videoFormat == VideoFormat.HDDVD) {

                // Take proper action according to playback setting
                bool hdExternal = MovingPicturesCore.Settings.UseExternalPlayer;

                // Launch external player if user has configured it for HD playback.
                if (hdExternal) {
                    LaunchHDPlayer(media);
                    logger.Info("HD Playback: Internal, Media={0}", media);
                    return;
                }
            }

            // We start listening to external player events
            listenToExternalPlayerEvents = true;

            // Enter full screen video and then play
            // prevents OSD showing before playback
            // Also appears that it enter playback faster!
            // Note: Playback Indicator will still be shown in skin
            // before playback actually starts ie. you're not going to see a black fullscreen
            GUIGraphicsContext.IsFullScreenVideo = true;
            GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO);

            // Play the file using the mediaportal player
            bool success = g_Player.Play(media.Trim(), g_Player.MediaType.Video, g_Player.SetResumeBDTitleState, _forcePlay);

            // We stop listening to external player events
            listenToExternalPlayerEvents = false;

            // Need to send Fullscreen for Blu-ray media
            GUIGraphicsContext.IsFullScreenVideo = true;
            GUIWindowManager.ActivateWindow((int)GUIWindow.Window.WINDOW_FULLSCREEN_VIDEO);

            // if the playback did not happen, reset the player
            if (!success) {
                logger.Info("Playback failed: Media={0}", media);
                resetPlayer();
            }
        }
Ejemplo n.º 31
0
        private void RunAnalyzeVideo()
        {
            Log.Info("Auto3D: Start Video Analysis");

            FrameGrabber fg = FrameGrabber.GetInstance();

            int maxAnalyzeSteps = 20;
            int treshold        = 5;

            VideoFormat[] vf = new VideoFormat[maxAnalyzeSteps + 1];

            int iStep = 0;

            while (_run && _bPlaying)
            {
                // wait 200 ms

                for (int i = 0; i < 10; i++)
                {
                    if (!_bPlaying) // if playing is stopped while we wait then return
                    {
                        return;
                    }

                    Thread.Sleep(20);
                }

                System.Drawing.Bitmap image = fg.GetCurrentImage();

                if (image != null)
                {
                    Bitmap fastCompareImage = new Bitmap(96, 96);

                    // set the resolutions the same to avoid cropping due to resolution differences
                    fastCompareImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                    //use a graphics object to draw the resized image into the bitmap
                    using (Graphics graphics = Graphics.FromImage(fastCompareImage))
                    {
                        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bicubic;
                        graphics.DrawImage(image, 0, 0, fastCompareImage.Width, fastCompareImage.Height);
                    }

                    // Lock the bitmap's bits.
                    Rectangle rect = new Rectangle(0, 0, fastCompareImage.Width, fastCompareImage.Height);
                    System.Drawing.Imaging.BitmapData bmpData = fastCompareImage.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);

                    double similarity = 0;

                    vf[iStep] = VideoFormat.Fmt2D; // assume normal format

                    if (bCheckSideBySide)
                    {
                        similarity = Auto3DAnalyzer.CheckFor3DFormat(bmpData, bmpData.Width / 2, bmpData.Height, true);
                    }

                    if (similarity == -1) // not bright enough for analysis
                    {
                        continue;
                    }

                    if (similarity > 0.925)
                    {
                        vf[iStep] = VideoFormat.Fmt3DSBS;
                    }
                    else
                    {
                        if (bCheckTopAndBottom)
                        {
                            similarity = Auto3DAnalyzer.CheckFor3DFormat(bmpData, bmpData.Width, bmpData.Height / 2, false);
                        }

                        if (similarity == -1) // not bright enough for analysis -> continue
                        {
                            continue;
                        }

                        if (similarity > 0.925)
                        {
                            vf[iStep] = VideoFormat.Fmt3DTAB;
                        }
                    }

                    fastCompareImage.UnlockBits(bmpData);

                    Log.Debug("Similarity: " + similarity + " - " + vf[iStep].ToString());
                }

                if (iStep > 3)
                {
                    // check if we can make a decision

                    int countNormal       = 0;
                    int countSideBySide3D = 0;
                    int countTopBottom3D  = 0;

                    for (int i = 0; i <= iStep; i++)
                    {
                        switch (vf[i])
                        {
                        case VideoFormat.Fmt2D:

                            countNormal++;
                            break;

                        case VideoFormat.Fmt3DSBS:

                            countSideBySide3D++;
                            break;

                        case VideoFormat.Fmt3DTAB:

                            countTopBottom3D++;
                            break;
                        }
                    }

                    Log.Debug("Results(" + iStep + ") - Normal=" + countNormal + " - SBS3D=" + countSideBySide3D + " - TB3D=" + countTopBottom3D);

                    if ((countSideBySide3D >= (countNormal + treshold)) || (countTopBottom3D >= (countNormal + treshold)) || (countSideBySide3D >= countNormal && iStep == maxAnalyzeSteps) || (countTopBottom3D >= countNormal && iStep == maxAnalyzeSteps))
                    {
                        VideoFormat videoFormat = countTopBottom3D > countSideBySide3D ? VideoFormat.Fmt3DTAB : VideoFormat.Fmt3DSBS;

                        if ((videoFormat == VideoFormat.Fmt3DSBS) || (videoFormat == VideoFormat.Fmt3DTAB))
                        {
                            if (videoFormat == VideoFormat.Fmt3DTAB)
                            {
                                Log.Info("Auto3D: Video Analysis Finished: Switch TV to TAB 3D");
                            }
                            else
                            {
                                Log.Info("Auto3D: Video Analysis Finished: Switch TV to SBS 3D");
                            }

                            if (bConvert3DTo2D)
                            {
                                switch (videoFormat)
                                {
                                case VideoFormat.Fmt3DSBS:

                                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.SideBySideTo2D;
                                    break;

                                case VideoFormat.Fmt3DTAB:

                                    GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.TopAndBottomTo2D;
                                    break;
                                }

                                _currentMode = videoFormat;
                            }
                            else
                            {
                                if (_activeDevice.SwitchFormat(_currentMode, videoFormat))
                                {
                                    switch (videoFormat)
                                    {
                                    case VideoFormat.Fmt3DSBS:

                                        GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.SideBySide;
                                        break;

                                    case VideoFormat.Fmt3DTAB:

                                        GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.TopAndBottom;
                                        break;
                                    }

                                    _currentMode = videoFormat;
                                }
                            }

                            UpdateSubtitleRenderFormat();
                        }
                        else
                        {
                            ManualSelect3DFormat(videoFormat);
                            UpdateSubtitleRenderFormat();
                        }

                        return; // exit thread
                    }
                    else
                    if ((_currentMode == VideoFormat.Fmt2D) && ((countNormal > countSideBySide3D + treshold) || (countNormal > countTopBottom3D + treshold)))
                    {
                        // current format is normal and video is normal too, we do not need to switch
                        Log.Info("Auto3D: Format is 2D. No switch necessary");
                        return; // exit thread
                    }
                    else
                    if (_currentMode != VideoFormat.Fmt2D)
                    {
                        // current format 3d and video is 2d, so we must switch back to normal
                        RunSwitchBack();
                        return; // exit thread
                    }
                    else
                    if (iStep > maxAnalyzeSteps)
                    {
                        // we could not make a decision within the maximum allowed steps
                        Log.Info("Auto3D: Video Analysis failed!");
                        return; // exit thread
                    }
                }

                iStep++;
            }
        }
Ejemplo n.º 32
0
        public async Task ConvertInFormat(Guid videoFileId, VideoFormat format)
        {
            FileDbModel result;

            var conversion =
                await _context.Conversions.FirstOrDefaultAsync(c =>
                                                               c.Source.FileId == videoFileId && c.VideoFormat == format);

            if (conversion?.Status == ConversionStatus.InProgress)
            {
                return;
            }

            if (conversion?.Status == ConversionStatus.Success)
            {
                result = conversion.Result;
            }

            else
            {
                var file = await _context.Files.FirstOrDefaultAsync(f => f.FileId == videoFileId)
                           ?? throw new FileNotFoundException();

                if (conversion == null)
                {
                    conversion = new ConversionDbModel
                    {
                        Source      = file,
                        Status      = ConversionStatus.InProgress,
                        Tryes       = 1,
                        VideoFormat = format
                    };
                    _context.Add(conversion);
                }
                else
                {
                    conversion.Tryes++; //todo maxTryes
                }
                await _context.SaveChangesAsync();

                if (format == VideoFormat.preview)
                {
                    result = await GenerateFilePreview(file);
                }

                else if (format == VideoFormat.gif)
                {
                    result = await GenerateFileGif(file);
                }

                else
                {
                    result = await ConvertVideoInternal(file, format);
                }

                _context.Files.Add(result);
                _context.SaveChanges();
            }

            _rabbitPublisher.Publish <VideoConvertedEventMessage>(new VideoConvertedEventMessage
            {
                Format   = format,
                SourceId = videoFileId,
                ResultId = result.FileId
            });
        }
        /// <summary>
        /// Generates commandline arguments used for encoding an video stream to h.264 format.
        /// Input is either stdin or file/avisynth script.
        /// </summary>
        /// <param name="inProfile">Encoding profile</param>
        /// <param name="bitrate">Target bitrate</param>
        /// <param name="hRes">Video width</param>
        /// <param name="vRes">Video height</param>
        /// <param name="pass">Encoding pass</param>
        /// <param name="fpsN">Framerate numerator</param>
        /// <param name="fpsD">Framerate denominator</param>
        /// <param name="stereo">Defines, which stereo encoding mode should be used</param>
        /// <param name="format">Image format</param>
        /// <param name="inFile">Path to input file</param>
        /// <param name="outFile">Path to output file</param>
        /// <returns>Commandline arguments</returns>
        public static string Generate(X264Profile inProfile, int bitrate, int hRes, int vRes, int pass, int fpsN, int fpsD, StereoEncoding stereo = StereoEncoding.None,
                                      VideoFormat format = VideoFormat.Unknown, string inFile = "input", string outFile = "output")
        {
            StringBuilder sb = new StringBuilder();
            if (inProfile != null)
            {
                bool display;
                X264Device device = X264Device.CreateDeviceList()[inProfile.TuneDevice];

                // AVC Profiles
                switch (inProfile.AVCProfile)
                {
                    case 0:
                        sb.Append("--profile baseline ");
                        break;
                    case 1:
                        sb.Append("--profile main ");
                        break;
                    default:
                        sb.Append("--profile high ");
                        break;
                }

                // AVC Levels
                if (inProfile.AVCLevel != 15) // unrestricted
                    sb.AppendFormat("--level {0} ", CLILevelNames[inProfile.AVCLevel]);

                // Blu-Ray compatibility
                if (inProfile.UseBluRayCompatibility)
                    sb.Append("--bluray-compat ");

                // x264 Presets
                if (!inProfile.CustomCommandLine.Contains("--preset"))
                {
                    switch (inProfile.Preset)
                    {
                        case 0: sb.Append("--preset ultrafast "); break;
                        case 1: sb.Append("--preset superfast "); break;
                        case 2: sb.Append("--preset veryfast "); break;
                        case 3: sb.Append("--preset faster "); break;
                        case 4: sb.Append("--preset fast "); break;
                        //case 5: sb.Append("--preset medium "); break; // default value
                        case 6: sb.Append("--preset slow "); break;
                        case 7: sb.Append("--preset slower "); break;
                        case 8: sb.Append("--preset veryslow "); break;
                        case 9: sb.Append("--preset placebo "); break;
                    }
                }

                // x264 Tunings
                if (!inProfile.CustomCommandLine.Contains("--tune"))
                {
                    switch (inProfile.Tuning)
                    {
                        case 1: sb.Append("--tune film "); break;
                        case 2: sb.Append("--tune animation "); break;
                        case 3: sb.Append("--tune grain "); break;
                        case 4: sb.Append("--tune psnr "); break;
                        case 5: sb.Append("--tune ssim "); break;
                        case 6: sb.Append("--tune fastdecode "); break;
                    }
                }

                // Encoding Modes
                int tempPass = pass;

                int tempBitrate = bitrate;
                int vbvBuf = GetVBVMaxrate(inProfile, device);

                if (tempBitrate <= 0)
                    tempBitrate = inProfile.VBRSetting;

                if (vbvBuf > 0 && tempBitrate > vbvBuf)   // limit Bitrate to max vbvbuf size
                    tempBitrate = vbvBuf;

                switch (inProfile.EncodingMode)
                {
                    case 0: // ABR
                        if (!inProfile.CustomCommandLine.Contains("--bitrate"))
                            sb.AppendFormat(AppSettings.CInfo, "--bitrate {0:0} ", tempBitrate);
                        break;
                    case 1: // Constant Quantizer
                        if (!inProfile.CustomCommandLine.Contains("--qp"))
                            sb.AppendFormat(AppSettings.CInfo, "--qp {0:0}", inProfile.QuantizerSetting);
                        break;
                    case 2: // automated 2 pass
                    case 3: // automated 3 pass
                        sb.AppendFormat(AppSettings.CInfo, "--pass {0:0} --bitrate {1:0} ", tempPass, tempBitrate);
                        break;
                    default:
                        if (!inProfile.CustomCommandLine.Contains("--crf") && inProfile.QualitySetting != 23)
                            sb.AppendFormat(AppSettings.CInfo, "--crf {0:0} ", inProfile.QualitySetting);
                        break;
                }

                // Slow 1st Pass
                if (!inProfile.CustomCommandLine.Contains("--slow-firstpass"))
                    if ((inProfile.UseSlowFirstPass) && inProfile.Preset < 9 && // 9 = placebo
                       ((inProfile.EncodingMode == 2) || // automated twopass
                        (inProfile.EncodingMode == 3)))  // automated threepass
                        sb.Append("--slow-firstpass ");

                // Threads
                if (!inProfile.CustomCommandLine.Contains("--thread-input"))
                    if (inProfile.UseThreadInput && inProfile.NumThreads == 1)
                        sb.Append("--thread-input ");
                if (!inProfile.CustomCommandLine.Contains("--threads"))
                    if (inProfile.NumThreads > 0)
                        sb.AppendFormat(AppSettings.CInfo, "--threads {0:0} ", inProfile.NumThreads);

                #region frame-type tab

                // H.264 Features
                if (inProfile.UseDeblocking)
                {
                    display = false;
                    switch (inProfile.Tuning)
                    {
                        case 1: if (inProfile.DeblockingStrength != -1 || inProfile.DeblockingThreshold != -1) display = true; break; // film
                        case 2: if (inProfile.DeblockingStrength != 1 || inProfile.DeblockingThreshold != 1) display = true; break; // animation
                        case 3: if (inProfile.DeblockingStrength != -2 || inProfile.DeblockingThreshold != -2) display = true; break; // grain
                        default: if (inProfile.DeblockingStrength != 0 || inProfile.DeblockingThreshold != 0) display = true;
                            break;
                    }

                    if (!inProfile.CustomCommandLine.Contains("--deblock "))
                        if (display)
                            sb.AppendFormat(AppSettings.CInfo, "--deblock {0:0}:{1:0} ", inProfile.DeblockingStrength,
                                            inProfile.DeblockingThreshold);
                }
                else
                {
                    if (!inProfile.CustomCommandLine.Contains("--no-deblock"))
                        if (inProfile.Preset != 0 && inProfile.Tuning != 7) // ultrafast preset and not fast decode tuning
                            sb.Append("--no-deblock ");
                }

                if (inProfile.AVCProfile > 0 && !inProfile.CustomCommandLine.Contains("--no-cabac"))
                {
                    if (!inProfile.UseCabac)
                    {
                        if (inProfile.Preset != 0 && inProfile.Tuning != 7) // ultrafast preset and not fast decode tuning
                            sb.Append("--no-cabac ");
                    }
                }

                // GOP Size
                int backupMaxGopSize = inProfile.MaxGopSize;
                int backupMinGopSize = inProfile.MinGopSize;

                inProfile.MaxGopSize = GetKeyInt(fpsN, fpsD, backupMaxGopSize, device, inProfile.GopCalculation);

                if (inProfile.MaxGopSize != 250) // default size
                {
                    if (inProfile.MaxGopSize == 0)
                        sb.Append("--keyint infinite ");
                    else
                        sb.AppendFormat(AppSettings.CInfo, "--keyint {0:0} ", inProfile.MaxGopSize);
                }

                if (!inProfile.UseBluRayCompatibility)
                {
                    inProfile.MinGopSize = GetMinKeyInt(fpsN, fpsD, backupMinGopSize, inProfile.MaxGopSize, device,
                                                        inProfile.GopCalculation);
                    if (inProfile.MinGopSize > (inProfile.MaxGopSize / 2 + 1))
                    {
                        inProfile.MinGopSize = inProfile.MaxGopSize / 2 + 1;
                    }
                    int Default = Math.Min(inProfile.MaxGopSize / 10, fpsN / fpsD);

                    if (inProfile.MinGopSize != Default) // (MIN(--keyint / 10,--fps)) is default
                        sb.AppendFormat(AppSettings.CInfo, "--min-keyint {0:0} ", inProfile.MinGopSize);
                }

                inProfile.MaxGopSize = backupMaxGopSize;
                inProfile.MinGopSize = backupMinGopSize;

                if (!inProfile.CustomCommandLine.Contains("--open-gop") && (inProfile.UseOpenGop || inProfile.UseBluRayCompatibility))
                    sb.Append("--open-gop ");

                // B-Frames
                inProfile.NumBFrames = GetBFrames(inProfile, device);
                if (inProfile.AVCProfile > 0 && inProfile.NumBFrames != X264Settings.GetDefaultNumberOfBFrames(inProfile.AVCLevel, inProfile.Tuning, inProfile.AVCProfile, device))
                    sb.AppendFormat(AppSettings.CInfo, "--bframes {0:0} ", inProfile.NumBFrames);

                if (inProfile.NumBFrames > 0)
                {
                    if (!inProfile.CustomCommandLine.Contains("--b-adapt"))
                    {
                        display = false;
                        if (inProfile.Preset > 5) // medium
                        {
                            if (inProfile.AdaptiveBFrames != 2)
                                display = true;
                        }
                        else if (inProfile.Preset > 0) // ultrafast
                        {
                            if (inProfile.AdaptiveBFrames != 1)
                                display = true;
                        }
                        else
                        {
                            if (inProfile.AdaptiveBFrames != 0)
                                display = true;
                        }
                        if (display)
                            sb.AppendFormat(AppSettings.CInfo, "--b-adapt {0:0} ", inProfile.AdaptiveBFrames);
                    }

                    inProfile.BPyramid = GetBPyramid(inProfile, device);
                    if (inProfile.NumBFrames > 1 && (inProfile.BPyramid != 2 && !inProfile.UseBluRayCompatibility || inProfile.BPyramid != 1 && inProfile.UseBluRayCompatibility))
                    {
                        switch (inProfile.BPyramid) // pyramid needs a minimum of 2 b frames
                        {
                            case 1: sb.Append("--b-pyramid strict "); break;
                            case 0: sb.Append("--b-pyramid none "); break;
                        }
                    }

                    if (!inProfile.CustomCommandLine.Contains("--no-weightb"))
                        if (!inProfile.UseWeightedPred && inProfile.Tuning != 7 && inProfile.Preset != 0) // no weightpredb + tuning != fastdecode + preset != ultrafast
                            sb.Append("--no-weightb ");
                }

                // B-Frames bias
                if (!inProfile.CustomCommandLine.Contains("--b-bias "))
                    if (inProfile.BFrameBias != 0)
                        sb.AppendFormat(AppSettings.CInfo, "--b-bias {0:0} ", inProfile.BFrameBias);

                // Other
                if (inProfile.UseAdaptiveIFrameDecision)
                {
                    if (!inProfile.CustomCommandLine.Contains("--scenecut "))
                        if (inProfile.NumExtraIFrames != 40 && inProfile.Preset != 0 ||
                            inProfile.NumExtraIFrames != 0 && inProfile.Preset == 0)
                            sb.AppendFormat(AppSettings.CInfo, "--scenecut {0:0} ", inProfile.NumExtraIFrames);
                }
                else
                {
                    if (!inProfile.CustomCommandLine.Contains("--no-scenecut"))
                        if (inProfile.Preset != 0)
                            sb.Append("--no-scenecut ");
                }

                // reference frames
                int iRefFrames = GetRefFrames(hRes, vRes, inProfile, device);
                if (iRefFrames != X264Settings.GetDefaultNumberOfRefFrames(inProfile.Preset, inProfile.Tuning, null, inProfile.AVCLevel, hRes, vRes))
                    sb.AppendFormat(AppSettings.CInfo, "--ref {0:0} ", iRefFrames);

                // WeightedPPrediction
                inProfile.PFrameWeightedPrediction = GetWeightp(inProfile, device);
                if (inProfile.PFrameWeightedPrediction != X264Settings.GetDefaultNumberOfWeightp(inProfile.Preset,
                                                                                                 inProfile.Tuning,
                                                                                                 inProfile.AVCProfile,
                                                                                                 inProfile.UseBluRayCompatibility))
                    sb.AppendFormat(AppSettings.CInfo, "--weightp {0:0} ", inProfile.PFrameWeightedPrediction);

                // Slicing
                inProfile.NumSlices = GetSlices(inProfile, device);
                if (inProfile.NumSlices != 0)
                    sb.AppendFormat(AppSettings.CInfo, "--slices {0:0} ", inProfile.NumSlices);

                if (!inProfile.CustomCommandLine.Contains("--slice-max-size "))
                    if (inProfile.MaxSliceSizeBytes != 0)
                        sb.AppendFormat(AppSettings.CInfo, "--slice-max-size {0:0} ", inProfile.MaxSliceSizeBytes);

                if (!inProfile.CustomCommandLine.Contains("--slice-max-mbs "))
                    if (inProfile.MaxSliceSizeBlocks != 0)
                        sb.AppendFormat(AppSettings.CInfo, "--slice-max-mbs {0:0} ", inProfile.MaxSliceSizeBlocks);

                #endregion

                #region rc tab

                if (!inProfile.CustomCommandLine.Contains("--qpmin"))
                    if (inProfile.QuantizerMin != 0)
                        sb.AppendFormat(AppSettings.CInfo, "--qpmin {0:0} ", inProfile.QuantizerMin);

                if (!inProfile.CustomCommandLine.Contains("--qpmax"))
                    if (inProfile.QuantizerMax != 69)
                        sb.AppendFormat(AppSettings.CInfo, "--qpmax {0:0} ", inProfile.QuantizerMax);

                if (!inProfile.CustomCommandLine.Contains("--qpstep"))
                    if (inProfile.QuantizerDelta != 4)
                        sb.AppendFormat(AppSettings.CInfo, "--qpstep {0:0} ", inProfile.QuantizerDelta);

                if (Math.Abs(inProfile.QuantizerRatioIP - 1.4F) > 0)
                {
                    display = true;
                    if (inProfile.Tuning == 3 && Math.Abs(inProfile.QuantizerRatioIP - 1.1F) <= 0)
                        display = false;

                    if (!inProfile.CustomCommandLine.Contains("--ipratio"))
                        if (display)
                            sb.AppendFormat(AppSettings.CInfo, "--ipratio {0:0} ", inProfile.QuantizerRatioIP);
                }

                if (Math.Abs(inProfile.QuantizerRatioPB - 1.3F) > 0)
                {
                    display = true;
                    if (inProfile.Tuning == 3 && Math.Abs(inProfile.QuantizerRatioPB - 1.1F) <= 0)
                        display = false;

                    if (!inProfile.CustomCommandLine.Contains("--pbratio"))
                        if (display)
                            sb.AppendFormat(AppSettings.CInfo, "--pbratio {0:0} ", inProfile.QuantizerRatioPB);
                }

                if (!inProfile.CustomCommandLine.Contains("--chroma-qp-offset"))
                    if (inProfile.ChromaQPOffset != 0)
                        sb.AppendFormat(AppSettings.CInfo, "--chroma-qp-offset {0:0} ", inProfile.ChromaQPOffset);

                if (inProfile.EncodingMode != 1) // doesn't apply to CQ mode
                {
                    inProfile.VBVBufSize = GetVBVBufsize(inProfile, device);
                    if (inProfile.VBVBufSize > 0)
                        sb.AppendFormat(AppSettings.CInfo, "--vbv-bufsize {0:0} ", inProfile.VBVBufSize);

                    inProfile.VBVMaxRate = GetVBVMaxrate(inProfile, device);
                    if (inProfile.VBVMaxRate > 0)
                        sb.AppendFormat(AppSettings.CInfo, "--vbv-maxrate {0:0} ", inProfile.VBVMaxRate);

                    if (!inProfile.CustomCommandLine.Contains("--vbv-init"))
                        if (Math.Abs(inProfile.VBVInitialBuffer - 0.9F) > 0)
                            sb.AppendFormat(AppSettings.CInfo, "--vbv-init {0:0.0} ", inProfile.VBVInitialBuffer);

                    if (!inProfile.CustomCommandLine.Contains("--ratetol"))
                        if (Math.Abs(inProfile.BitrateVariance - 1.0F) > 0)
                            sb.AppendFormat(AppSettings.CInfo, "--ratetol {0:0.0} ", inProfile.BitrateVariance);

                    if (!inProfile.CustomCommandLine.Contains("--qcomp"))
                    {
                        display = true;
                        if ((inProfile.Tuning == 3 && Math.Abs(inProfile.QuantizerCompression - 0.8F) <= 0) || (inProfile.Tuning != 3 && Math.Abs(inProfile.QuantizerCompression - 0.6F) <= 0))
                            display = false;
                        if (display)
                            sb.AppendFormat(AppSettings.CInfo, "--qcomp {0:0.0} ", inProfile.QuantizerCompression);
                    }

                    if (inProfile.EncodingMode > 1) // applies only to twopass
                    {
                        if (!inProfile.CustomCommandLine.Contains("--cplxblur"))
                            if (inProfile.TempBlurFrameComplexity != 20)
                                sb.AppendFormat(AppSettings.CInfo, "--cplxblur {0:0} ", inProfile.TempBlurFrameComplexity);

                        if (!inProfile.CustomCommandLine.Contains("--qblur"))
                            if (Math.Abs(inProfile.TempBlurQuant - 0.5F) > 0)
                                sb.AppendFormat(AppSettings.CInfo, "--qblur {0:0.0} ", inProfile.TempBlurQuant);
                    }
                }

                // Dead Zones
                if (!inProfile.CustomCommandLine.Contains("--deadzone-inter"))
                {
                    display = true;
                    if ((inProfile.Tuning != 3 && inProfile.DeadZoneInter == 21 && inProfile.DeadZoneIntra == 11) ||
                        (inProfile.Tuning == 3 && inProfile.DeadZoneInter == 6 && inProfile.DeadZoneIntra == 6))
                        display = false;
                    if (display)
                        sb.AppendFormat(AppSettings.CInfo, "--deadzone-inter {0:0} ", inProfile.DeadZoneInter);
                }

                if (!inProfile.CustomCommandLine.Contains("--deadzone-intra"))
                {
                    display = true;
                    if ((inProfile.Tuning != 3 && inProfile.DeadZoneIntra == 11) || (inProfile.Tuning == 3 && inProfile.DeadZoneIntra == 6))
                        display = false;
                    if (display)
                        sb.AppendFormat(AppSettings.CInfo, "--deadzone-intra {0:0} ", inProfile.DeadZoneIntra);
                }

                // Disable Macroblok Tree
                if (!inProfile.UseMBTree)
                {
                    if (!inProfile.CustomCommandLine.Contains("--no-mbtree"))
                        if (inProfile.Preset > 0) // preset veryfast
                            sb.Append("--no-mbtree ");
                }
                else
                {
                    // RC Lookahead
                    if (!inProfile.CustomCommandLine.Contains("--rc-lookahead"))
                    {
                        display = false;
                        switch (inProfile.Preset)
                        {
                            case 0:
                            case 1: if (inProfile.NumFramesLookahead != 0) display = true; break;
                            case 2: if (inProfile.NumFramesLookahead != 10) display = true; break;
                            case 3: if (inProfile.NumFramesLookahead != 20) display = true; break;
                            case 4: if (inProfile.NumFramesLookahead != 30) display = true; break;
                            case 5: if (inProfile.NumFramesLookahead != 40) display = true; break;
                            case 6: if (inProfile.NumFramesLookahead != 50) display = true; break;
                            case 7:
                            case 8:
                            case 9: if (inProfile.NumFramesLookahead != 60) display = true; break;
                        }
                        if (display)
                            sb.AppendFormat("--rc-lookahead {0:0} ", inProfile.NumFramesLookahead);
                    }
                }

                // AQ-Mode
                if (inProfile.EncodingMode != 1)
                {
                    if (!inProfile.CustomCommandLine.Contains("--aq-mode"))
                    {
                        if (inProfile.AdaptiveQuantizersMode != X264Settings.GetDefaultAQMode(inProfile.Preset, inProfile.Tuning))
                            sb.AppendFormat("--aq-mode {0:0} ", inProfile.AdaptiveQuantizersMode);
                    }

                    if (inProfile.AdaptiveQuantizersMode > 0)
                    {
                        display = false;
                        switch (inProfile.Tuning)
                        {
                            case 2: if (Math.Abs(inProfile.AdaptiveQuantizersStrength - 0.6F) > 0) display = true; break;
                            case 3: if (Math.Abs(inProfile.AdaptiveQuantizersStrength - 0.5F) > 0) display = true; break;
                            case 7: if (Math.Abs(inProfile.AdaptiveQuantizersStrength - 1.3F) > 0) display = true; break;
                            default: if (Math.Abs(inProfile.AdaptiveQuantizersStrength - 1.0F) > 0) display = true; break;
                        }
                        if (!inProfile.CustomCommandLine.Contains("--aq-strength"))
                            if (display)
                                sb.AppendFormat(AppSettings.CInfo, "--aq-strength {0:0.0} ", inProfile.AdaptiveQuantizersStrength);
                    }
                }

                // custom matrices
                if (inProfile.AVCProfile > 1 && inProfile.QuantizerMatrix > 0)
                {
                    switch (inProfile.QuantizerMatrix)
                    {
                        case 1: if (!inProfile.CustomCommandLine.Contains("--cqm")) sb.Append("--cqm \"jvt\" "); break;
                    }
                }
                #endregion

                #region analysis tab

                // Disable Chroma Motion Estimation
                if (!inProfile.CustomCommandLine.Contains("--no-chroma-me"))
                    if (!inProfile.UseChromaMotionEstimation)
                        sb.Append("--no-chroma-me ");

                // Motion Estimation Range
                if (!inProfile.CustomCommandLine.Contains("--merange"))
                {
                    if ((inProfile.Preset <= 7 && inProfile.MotionEstimationRange != 16) ||
                        (inProfile.Preset >= 8 && inProfile.MotionEstimationRange != 24))
                        sb.AppendFormat("--merange {0:0} ", inProfile.MotionEstimationRange);
                }

                // ME Type
                if (!inProfile.CustomCommandLine.Contains("--me "))
                {
                    display = false;
                    switch (inProfile.Preset)
                    {
                        case 0:
                        case 1: if (inProfile.MotionEstimationAlgorithm != 0) display = true; break;
                        case 2:
                        case 3:
                        case 4:
                        case 5: if (inProfile.MotionEstimationAlgorithm != 1) display = true; break;
                        case 6:
                        case 7:
                        case 8: if (inProfile.MotionEstimationAlgorithm != 2) display = true; break;
                        case 9: if (inProfile.MotionEstimationAlgorithm != 4) display = true; break;
                    }

                    if (display)
                    {
                        switch (inProfile.MotionEstimationAlgorithm)
                        {
                            case 0: sb.Append("--me dia "); break;
                            case 1: sb.Append("--me hex "); break;
                            case 2: sb.Append("--me umh "); break;
                            case 3: sb.Append("--me esa "); break;
                            case 4: sb.Append("--me tesa "); break;
                        }
                    }

                }

                if (!inProfile.CustomCommandLine.Contains("--direct "))
                {
                    display = false;
                    if (inProfile.Preset > 5) // preset medium
                    {
                        if (inProfile.MVPredictionMod != 3)
                            display = true;
                    }
                    else if (inProfile.MVPredictionMod != 1)
                        display = true;

                    if (display)
                    {
                        switch (inProfile.MVPredictionMod)
                        {
                            case 0: sb.Append("--direct none "); break;
                            case 1: sb.Append("--direct spatial "); break;
                            case 2: sb.Append("--direct temporal "); break;
                            case 3: sb.Append("--direct auto "); break;
                        }
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--nr "))
                    if (inProfile.NoiseReduction > 0)
                        sb.AppendFormat("--nr {0:0} ", inProfile.NoiseReduction);

                // subpel refinement
                if (!inProfile.CustomCommandLine.Contains("--subme "))
                {
                    display = false;
                    switch (inProfile.Preset)
                    {
                        case 0: if (inProfile.SubPixelRefinement != 0) display = true; break;
                        case 1: if (inProfile.SubPixelRefinement != 1) display = true; break;
                        case 2: if (inProfile.SubPixelRefinement != 2) display = true; break;
                        case 3: if (inProfile.SubPixelRefinement != 4) display = true; break;
                        case 4: if (inProfile.SubPixelRefinement != 6) display = true; break;
                        case 5: if (inProfile.SubPixelRefinement != 7) display = true; break;
                        case 6: if (inProfile.SubPixelRefinement != 8) display = true; break;
                        case 7: if (inProfile.SubPixelRefinement != 9) display = true; break;
                        case 8: if (inProfile.SubPixelRefinement != 10) display = true; break;
                        case 9: if (inProfile.SubPixelRefinement != 11) display = true; break;
                    }
                    if (display)
                        sb.AppendFormat("--subme {0:0} ", inProfile.SubPixelRefinement);
                }

                // macroblock types
                if (!inProfile.CustomCommandLine.Contains("--partitions "))
                {
                    bool bExpectedP8X8Mv = true;
                    bool bExpectedB8X8Mv = true;
                    bool bExpectedI4X4Mv = true;
                    bool bExpectedI8X8Mv = true;
                    bool bExpectedP4X4Mv = true;

                    switch (inProfile.Preset)
                    {
                        case 0:
                            bExpectedP8X8Mv = false;
                            bExpectedB8X8Mv = false;
                            bExpectedI4X4Mv = false;
                            bExpectedI8X8Mv = false;
                            bExpectedP4X4Mv = false;
                            break;
                        case 1:
                            bExpectedP8X8Mv = false;
                            bExpectedB8X8Mv = false;
                            bExpectedP4X4Mv = false;
                            break;
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                            bExpectedP4X4Mv = false;
                            break;
                    }
                    if (inProfile.Tuning == 7 && bExpectedP8X8Mv)
                        bExpectedP4X4Mv = true;

                    if (inProfile.AVCProfile < 2)
                        bExpectedI8X8Mv = false;

                    if (bExpectedP8X8Mv != inProfile.MacroBlocksPartitionsP8X8 || bExpectedB8X8Mv != inProfile.MacroBlocksPartitionsB8X8
                        || bExpectedI4X4Mv != inProfile.MacroBlocksPartitionsI4X4 || bExpectedI8X8Mv != inProfile.MacroBlocksPartitionsI8X8
                        || bExpectedP4X4Mv != inProfile.MacroBlocksPartitionsP4X4)
                    {
                        if (inProfile.MacroBlocksPartitionsP8X8 ||
                            inProfile.MacroBlocksPartitionsB8X8 ||
                            inProfile.MacroBlocksPartitionsI4X4 ||
                            inProfile.MacroBlocksPartitionsI8X8 ||
                            inProfile.MacroBlocksPartitionsP4X4)
                        {
                            sb.Append("--partitions ");
                            if (inProfile.MacroBlocksPartitionsI4X4 &&
                                    inProfile.MacroBlocksPartitionsI8X8 &&
                                    inProfile.MacroBlocksPartitionsP4X4 &&
                                    inProfile.MacroBlocksPartitionsP8X8 &&
                                    inProfile.MacroBlocksPartitionsB8X8)
                                sb.Append("all ");
                            else
                            {
                                if (inProfile.MacroBlocksPartitionsP8X8) // default is checked
                                    sb.Append("p8x8,");
                                if (inProfile.MacroBlocksPartitionsB8X8) // default is checked
                                    sb.Append("b8x8,");
                                if (inProfile.MacroBlocksPartitionsI4X4) // default is checked
                                    sb.Append("i4x4,");
                                if (inProfile.MacroBlocksPartitionsP4X4) // default is unchecked
                                    sb.Append("p4x4,");
                                if (inProfile.MacroBlocksPartitionsI8X8) // default is checked
                                    sb.Append("i8x8");
                                if (sb.ToString().EndsWith(","))
                                    sb.Remove(sb.Length - 1, 1);
                            }

                            if (!sb.ToString().EndsWith(" "))
                                sb.Append(" ");
                        }
                        else
                            sb.Append("--partitions none ");
                    }
                }

                if (inProfile.AVCProfile > 1 && !inProfile.CustomCommandLine.Contains("--no-8x8dct"))
                    if (!inProfile.MacroBlocksPartitionsAdaptiveDCT)
                        if (inProfile.Preset > 0)
                            sb.Append("--no-8x8dct ");

                // Trellis
                if (!inProfile.CustomCommandLine.Contains("--trellis "))
                {
                    display = false;
                    switch (inProfile.Preset)
                    {
                        case 0:
                        case 1:
                        case 2: if (inProfile.Trellis != 0) display = true; break;
                        case 3:
                        case 4:
                        case 5:
                        case 6: if (inProfile.Trellis != 1) display = true; break;
                        case 7:
                        case 8:
                        case 9: if (inProfile.Trellis != 2) display = true; break;
                    }
                    if (display)
                        sb.AppendFormat("--trellis {0:0} ", inProfile.Trellis);
                }

                if (!inProfile.CustomCommandLine.Contains("--psy-rd "))
                {
                    if (inProfile.SubPixelRefinement > 5)
                    {
                        display = false;
                        switch (inProfile.Tuning)
                        {
                            case 1: if ((Math.Abs(inProfile.PsyRDStrength - 1.0F) > 0) || (Math.Abs(inProfile.PsyTrellisStrength - 0.15F) > 0)) display = true; break;
                            case 2: if ((Math.Abs(inProfile.PsyRDStrength - 0.4F) > 0) || (Math.Abs(inProfile.PsyTrellisStrength - 0.0F) > 0)) display = true; break;
                            case 3: if ((Math.Abs(inProfile.PsyRDStrength - 1.0F) > 0) || (Math.Abs(inProfile.PsyTrellisStrength - 0.25F) > 0)) display = true; break;
                            case 7: if ((Math.Abs(inProfile.PsyRDStrength - 1.0F) > 0) || (Math.Abs(inProfile.PsyTrellisStrength - 0.2F) > 0)) display = true; break;
                            default: if ((Math.Abs(inProfile.PsyRDStrength - 1.0F) > 0) || (Math.Abs(inProfile.PsyTrellisStrength - 0.0F) > 0)) display = true; break;
                        }

                        if (display)
                            sb.AppendFormat(AppSettings.CInfo, "--psy-rd {0:0.00}:{1:0.00} ", inProfile.PsyRDStrength, inProfile.PsyTrellisStrength);
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--no-mixed-refs"))
                    if (inProfile.UseNoMixedReferenceFrames)
                        if (inProfile.Preset >= 4) // preset fast
                            sb.Append("--no-mixed-refs ");

                if (!inProfile.CustomCommandLine.Contains("--no-dct-decimate"))
                    if (inProfile.UseNoDCTDecimation)
                        if (inProfile.Tuning != 3) // tune grain
                            sb.Append("--no-dct-decimate ");

                if (!inProfile.CustomCommandLine.Contains("--no-fast-pskip"))
                    if (inProfile.UseNoFastPSkip)
                        if (inProfile.Preset != 9) // preset placebo
                            sb.Append("--no-fast-pskip ");

                if (!inProfile.CustomCommandLine.Contains("--no-psy"))
                    if (inProfile.UseNoPsychovisualEnhancements && (inProfile.Tuning != 5 && inProfile.Tuning != 6))
                        sb.Append("--no-psy ");

                inProfile.UseAccessUnitDelimiters = GetAud(inProfile, device);
                if (inProfile.UseAccessUnitDelimiters && !inProfile.UseBluRayCompatibility)
                    sb.Append("--aud ");

                inProfile.HRDInfo = GetNalHrd(inProfile, device);
                switch (inProfile.HRDInfo)
                {
                    case 1: if (!inProfile.UseBluRayCompatibility) sb.Append("--nal-hrd vbr "); break;
                    case 2: sb.Append("--nal-hrd cbr "); break;
                }

                if (!inProfile.CustomCommandLine.Contains("--non-deterministic"))
                    if (inProfile.UseNonDeterministic)
                        sb.Append("--non-deterministic ");
                #endregion

                #region misc tab

                if (!inProfile.CustomCommandLine.Contains("--psnr"))
                    if (inProfile.UsePSNRCalculation)
                        sb.Append("--psnr ");

                if (!inProfile.CustomCommandLine.Contains("--ssim"))
                    if (inProfile.UseSSIMCalculation)
                        sb.Append("--ssim ");

                if (!inProfile.CustomCommandLine.Contains("--range "))
                    switch (inProfile.VUIRange)
                    {
                        case 1:
                            sb.AppendFormat("--range tv ");
                            break;
                        case 2:
                            sb.Append("--range pc ");
                            break;
                    }

                #endregion

                #region input / ouput / custom

                string customSarValue = string.Empty;

                Dar? d = new Dar((ulong)hRes, (ulong)vRes);

                if (inProfile.UseAutoSelectSAR)
                {
                    int tempValue = GetSar(inProfile, d, hRes, vRes, out customSarValue, String.Empty);
                    inProfile.ForceSAR = tempValue;
                }

                if (inProfile.UseAutoSelectColorSettings)
                {
                    inProfile.ColorPrimaries = GetColorprim(inProfile, format);

                    inProfile.Transfer = GetTransfer(inProfile, format);

                    inProfile.ColorMatrix = GetColorMatrix(inProfile, format);
                }

                if (device.BluRay)
                {
                    if (inProfile.InterlaceMode < 2)
                        inProfile.InterlaceMode = GetInterlacedMode(format);

                    inProfile.UseFakeInterlaced = GetFakeInterlaced(inProfile, format, fpsN, fpsD);

                    inProfile.UseForcePicStruct = GetPicStruct(inProfile, format);

                    inProfile.Pulldown = GetPulldown(inProfile, format, fpsN, fpsD);
                }
                else
                {
                    if (inProfile.InterlaceMode == 0)
                        inProfile.InterlaceMode = GetInterlacedMode(format);

                    if (inProfile.Pulldown == 0)
                        inProfile.Pulldown = GetPulldown(inProfile, format, fpsN, fpsD);
                }

                if (!inProfile.CustomCommandLine.Contains("--bff") &&
                    !inProfile.CustomCommandLine.Contains("--tff"))
                {
                    switch (inProfile.InterlaceMode)
                    {
                        case 2: sb.Append("--bff "); break;
                        case 3: sb.Append("--tff "); break;
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--fake-interlaced"))
                {
                    if (inProfile.UseFakeInterlaced && inProfile.InterlaceMode == 1)
                        sb.Append("--fake-interlaced ");
                }

                if (!inProfile.CustomCommandLine.Contains("--pic-struct"))
                {
                    if (inProfile.UseForcePicStruct && inProfile.InterlaceMode == 1 && inProfile.Pulldown == 0)
                        sb.Append("--pic-struct ");
                }

                if (!inProfile.CustomCommandLine.Contains("--colorprim"))
                {
                    switch (inProfile.ColorPrimaries)
                    {
                        case 0: break;
                        case 1: sb.Append("--colorprim bt709 "); break;
                        case 2: sb.Append("--colorprim bt470m "); break;
                        case 3: sb.Append("--colorprim bt470bg "); break;
                        case 4: sb.Append("--colorprim smpte170m "); break;
                        case 5: sb.Append("--colorprim smpte240m "); break;
                        case 6: sb.Append("--colorprim film "); break;
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--transfer"))
                {
                    switch (inProfile.Transfer)
                    {
                        case 0: break;
                        case 1: sb.Append("--transfer bt709 "); break;
                        case 2: sb.Append("--transfer bt470m "); break;
                        case 3: sb.Append("--transfer bt470bg "); break;
                        case 4: sb.Append("--transfer linear "); break;
                        case 5: sb.Append("--transfer log100 "); break;
                        case 6: sb.Append("--transfer log316 "); break;
                        case 7: sb.Append("--transfer smpte170m "); break;
                        case 8: sb.Append("--transfer smpte240m "); break;
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--colormatrix"))
                {
                    switch (inProfile.ColorMatrix)
                    {
                        case 0: break;
                        case 1: sb.Append("--colormatrix bt709 "); break;
                        case 2: sb.Append("--colormatrix fcc "); break;
                        case 3: sb.Append("--colormatrix bt470bg "); break;
                        case 4: sb.Append("--colormatrix smpte170m "); break;
                        case 5: sb.Append("--colormatrix smpte240m "); break;
                        case 6: sb.Append("--colormatrix GBR "); break;
                        case 7: sb.Append("--colormatrix YCgCo "); break;
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--pulldown"))
                {
                    switch (inProfile.Pulldown)
                    {
                        case 0: break;
                        case 1: break;
                        case 2: sb.Append("--pulldown 22 "); break;
                        case 3: sb.Append("--pulldown 32 "); break;
                        case 4: sb.Append("--pulldown 64 "); break;
                        case 5: sb.Append("--pulldown double "); break;
                        case 6: sb.Append("--pulldown triple "); break;
                        case 7: sb.Append("--pulldown euro "); break;
                    }
                }

                if (!String.IsNullOrEmpty(inProfile.CustomCommandLine)) // add custom encoder options
                    sb.Append(Regex.Replace(inProfile.CustomCommandLine, @"\r\n?|\n", string.Empty).Trim() + " ");

                if (!inProfile.CustomCommandLine.Contains("--sar"))
                {
                    switch (inProfile.ForceSAR)
                    {
                        case 0:
                            {
                                if (!String.IsNullOrEmpty(customSarValue))
                                    sb.Append("--sar " + customSarValue + " ");
                                break;
                            }
                        case 1: sb.Append("--sar 1:1 "); break;
                        case 2: sb.Append("--sar 4:3 "); break;
                        case 3: sb.Append("--sar 8:9 "); break;
                        case 4: sb.Append("--sar 10:11 "); break;
                        case 5: sb.Append("--sar 12:11 "); break;
                        case 6: sb.Append("--sar 16:11 "); break;
                        case 7: sb.Append("--sar 32:27 "); break;
                        case 8: sb.Append("--sar 40:33 "); break;
                        case 9: sb.Append("--sar 64:45 "); break;
                    }
                }

                if (!inProfile.CustomCommandLine.Contains("--frame-packing"))
                {
                    if (stereo != StereoEncoding.None)
                        sb.Append("--frame-packing 3 ");
                }

                //add the rest of the commandline regarding the output
                if ((inProfile.EncodingMode == 2 || inProfile.EncodingMode == 3) && (tempPass == 1))
                    sb.Append("--output NUL ");
                else if (!String.IsNullOrEmpty(outFile))
                    sb.AppendFormat("--output \"{0}\" ", outFile);

                if (!String.IsNullOrEmpty(inFile))
                {
                    if (String.CompareOrdinal(inFile, "-") == 0)
                        sb.AppendFormat("--demuxer y4m - ");
                    else
                        sb.AppendFormat("\"{0}\" ", inFile);
                }

                #endregion
            }
            return sb.ToString();
        }
Ejemplo n.º 34
0
        private void doCompression(VideoFormat videoFormat,string tmpAviFilePath, DicomElement dicomElement)
        {
            string format = videoFormat.ToString().ToLower();
            string outputFileName = Path.GetFileNameWithoutExtension(dicomElement.FilePath) + "." + format;
            string outputFolderPath = Settings.Default.ExportPath + dicomElement.GetSubFolderPath(format);
            Directory.CreateDirectory(outputFolderPath);
            string outputFilePath = Path.Combine(outputFolderPath, outputFileName);
            if (File.Exists(outputFilePath))
            {
                outputFilePath = renameToNonExistentFileName(outputFilePath);
            }

            if (videoFormat == VideoFormat.M4V)
            {
                executeMultiPassesCommandsForM4v(tmpAviFilePath, outputFilePath);

            }
            else
            {
                executeFFmpegCommand(createDefaultArguments(videoFormat, tmpAviFilePath, outputFilePath, dicomElement));
            }
        }
Ejemplo n.º 35
0
        private string createDefaultArguments(VideoFormat videoFormat, string inputFilePath, string outputFilePath, DicomElement dicomElement)
        {
            // for ffmpeg testing
            //ffmpeg -i test-video.avi -r 2 -qscale 31 -f m4v m5.mpg
            // mpeg1 supports only specific fps values, see mpeg12data.c from ffmpeg source
            string format = videoFormat.ToString().ToLower();

            int originalFps;
            string strOriginalFps = dicomElement.DicomFile.DataSet[DicomTags.CineRate].GetString(0, "");
            if (int.TryParse(strOriginalFps, out originalFps) == false)
            {
                originalFps = Settings.Default.Fps;
            }

            int fps = (videoFormat == VideoFormat.MPEG) ? 24 : originalFps;

            return @"-i " + inputFilePath
                + " -r " + fps
                + " -qscale " + Settings.Default.Quality
                + " -f " + format
                + " \"" + outputFilePath + "\"";
        }
Ejemplo n.º 36
0
 /* at this point, the buffer must be a complete dirac packet */
 private void Dispatch(Buffer b)
 {
     if (b.GetInt(5) != b.Size())
         throw new Exception("Incorrect buffer sizes");
     byte c = b.GetByte(4);
     switch(c) {
     case 0x00:
         VideoFormat tmp = new VideoFormat(b);
         if(format == null) {
         format = tmp;
         status = Status.OK;
         } else if(!tmp.Equals(format)) {
         throw new Exception("Stream Error: Inequal Video Formats");
         }
         break;
     case 0x10:
         status = Status.DONE;
         break;
     case 0x20:
     case 0x30:
         break;
     default:
         if(format == null)
             throw new Exception("Stream Error: Picture Before Header");
         Picture pic = new Picture(b, this);
         pic.Parse();
         inQueue.Push(pic);
         break;
     }
 }
Ejemplo n.º 37
0
 public VideoInfo()
 {
     FPS = float.NaN;
     Format = string.Empty;
     FormatProfile = string.Empty;
     StreamId = int.MinValue;
     VtsId = int.MinValue;
     TrackId = int.MinValue;
     TempFile = string.Empty;
     Interlaced = false;
     PicSize = VideoFormat.Unknown;
     DemuxStreamId = int.MinValue;
     DemuxStreamNames = new List<string>();
     DemuxPlayList = int.MinValue;
     Width = int.MinValue;
     Height = int.MinValue;
     FrameCount = long.MinValue;
     Encoded = false;
     IsRawStream = false;
     StreamSize = ulong.MinValue;
     Length = double.NaN;
     AspectRatio = float.NaN;
     Bitrate = long.MinValue;
     CropRect = new Rectangle();
     FrameRateEnumerator = int.MinValue;
     FrameRateDenominator = int.MinValue;
 }
        private static int GetInterlacedMode(VideoFormat format)
        {
            int iMode;

            switch (format)
            {
                case VideoFormat.Videoformat480I:
                case VideoFormat.Videoformat576I:
                case VideoFormat.Videoformat1080I:
                    iMode = 2;
                    break;
                default:
                    iMode = 1;
                    break;
            }

            return iMode;
        }
Ejemplo n.º 39
0
 public void BeginConversion(string vidPath, VideoFormat vidFormat)
 {
     BeginConversion(vidPath, Path.GetDirectoryName(vidPath), vidFormat);
 }
 private static int GetColorMatrix(X264Profile inProfile, VideoFormat format)
 {
     int matrix = inProfile.ColorMatrix;
     switch (format)
     {
         case VideoFormat.Videoformat480I:
         case VideoFormat.Videoformat480P:
             matrix = 4;
             break;
         case VideoFormat.Videoformat576I:
         case VideoFormat.Videoformat576P:
             matrix = 3;
             break;
         case VideoFormat.Videoformat720P:
         case VideoFormat.Videoformat1080I:
         case VideoFormat.Videoformat1080P:
             matrix = 1;
             break;
     }
     return matrix;
 }
        private static int GetPulldown(X264Profile inProfile, VideoFormat format, int fpsN, int fpsD)
        {
            int pullDown = inProfile.Pulldown;

            switch (format)
            {
                case VideoFormat.Unknown:
                    break;
                case VideoFormat.Videoformat480I:
                    break;
                case VideoFormat.Videoformat480P:
                    pullDown = 3;
                    break;
                case VideoFormat.Videoformat576I:
                    break;
                case VideoFormat.Videoformat576P:
                    break;
                case VideoFormat.Videoformat720P:
                    if (((fpsN == 30000) && (fpsD == 1001)) || ((fpsN == 25000) && (fpsD == 1000))) // 29.976 or 25 fps
                        pullDown = 5;
                    break;
                case VideoFormat.Videoformat1080I:
                    break;
                case VideoFormat.Videoformat1080P:
                    break;
            }

            return pullDown;
        }
Ejemplo n.º 42
0
 /// <summary>Create with video stream.</summary>
 public AviWriter(System.IO.Stream outputAvi, string fourCC, VideoFormat videoFormat)
     : this(outputAvi, fourCC, videoFormat, null)
 {
 }
Ejemplo n.º 43
0
        // start playback of a file (using known format)
        private void playFile(string media, VideoFormat videoFormat)
        {
            logger.Debug("Processing media for playback: File={0}, VideoFormat={1}", media, videoFormat);

            // HD Playback
            if (videoFormat == VideoFormat.Bluray || videoFormat == VideoFormat.HDDVD) {

                // Take proper action according to playback setting
                bool hdExternal = MovingPicturesCore.Settings.UseExternalPlayer;

                // Launch external player if user has configured it for HD playback.
                if (hdExternal) {
                    LaunchHDPlayer(media);
                    return;
                }

                // Alternate playback HD content (without menu)
                string newMedia = videoFormat.GetMainFeatureFilePath(media);
                 if (newMedia != null) {
                    // Check if the stream extension is in the mediaportal extension list.
                    if (Utility.IsMediaPortalVideoFile(newMedia)) {
                        media = newMedia;
                    }
                    else {
                        // Show a dialog to the user that explains how to configure the alternate playback
                        string ext = (videoFormat == VideoFormat.Bluray) ? ".M2TS" : ".EVO";
                        logger.Info("HD Playback: extension '{0}' is missing from the mediaportal configuration.", ext);
                        _gui.ShowMessage(Translation.PlaybackFailedHeader, String.Format(Translation.PlaybackFailed, ext));
                        resetPlayer();
                        return;
                    }
                }

                logger.Info("HD Playback: Internal, Media={0}", media);
            }

            // We start listening to external player events
            listenToExternalPlayerEvents = true;

            // Play the file using the mediaportal player
            bool success = g_Player.Play(media.Trim());

            // We stop listening to external player events
            listenToExternalPlayerEvents = false;

            // if the playback started and we are still playing go full screen (internal player)
            if (success && g_Player.Playing)
                g_Player.ShowFullScreenWindow();
            else if (!success) {
                // if the playback did not happen, reset the player
                logger.Info("Playback failed: Media={0}", media);
                resetPlayer();
            }
        }
Ejemplo n.º 44
0
 public static extern Int32 GetVideoFormat(UInt16 index, Int32 IndexFormat, out VideoFormat videoFormat);
Ejemplo n.º 45
0
        /// <summary>Create Hdrl</summary>
        private void WriteHdrlList(RiffList hdrlList, string fourCC, VideoFormat videoFormat, AudioFormat audioFormat, int videoFrames, int audioFrames)
        {
            // - xxxx.avi - RIFF - AVI
            //   |
            //   - LIST - hdrl         : Header List
            //   | |
            //   | |-- avih            : Main AVI Header
            //   | |
            //   | |-- LIST - strl     : Stream Header List
            //   | |   |-- strh        : Stream Header
            //   | |   +-- strf        : BITMAPINFOHEADER
            //   | |
            //   | +-- LIST - strl     : Stream Header List
            //   |     |-- strh        : Stream Header
            //   |     +-- strf        : WAVEFORMATEX
            //   |
            //   - LIST - movi
            //   | |
            //   | |-- 00dc            : stream 0 Video Chunk
            //   | |-- 01wb            : stream 1 Audio Chunk
            //   | |-- 00dc
            //   | |-- 01wb
            //   | +-- ....
            //   |
            //   + idx1
            //
            // some avi files insert JUNK chunk before 'LIST - movi' to align 2048 bytes boundary.
            // but I cant find any reason to align 2048 bytes boundary.

            if (videoFormat == null)
            {
                throw new ArgumentNullException("videoFormat");
            }

            int streams = audioFormat == null ? 1 : 2;

            // LISTチャンク'hdrl'を追加
            // 'hdrl' リストは AVI メイン ヘッダーで始まり、このメイン ヘッダーは 'avih' チャンクに含まれている。
            // メイン ヘッダーには、ファイル内のストリーム数、AVI シーケンスの幅と高さなど、AVI ファイル全体に関するグローバル情報が含まれる。
            // メイン ヘッダー チャンクは、AVIMAINHEADER 構造体で構成されている。
            {
                var chunk = hdrlList.CreateChunk("avih");
                var avih  = new AVIMAINHEADER();
                avih.dwMicroSecPerFrame    = (uint)(1 / videoFormat.FramesPerSec * 1000 * 1000);
                avih.dwMaxBytesPerSec      = 25000;  // ffmpegと同じ値に
                avih.dwFlags               = 0x0910; // ffmpegと同じ値に
                avih.dwTotalFrames         = (uint)videoFrames;
                avih.dwStreams             = (uint)streams;
                avih.dwSuggestedBufferSize = 0x100000;
                avih.dwWidth               = (uint)videoFormat.Width;
                avih.dwHeight              = (uint)videoFormat.Height;

                var data = StructureToBytes(avih);
                chunk.Write(data);
                chunk.Close();
            }

            // メイン ヘッダーの次には、1 つ以上の 'strl' リストが続く。'strl' リストは各データ ストリームごとに必要である。
            // 各 'strl' リストには、ファイル内の単一のストリームに関する情報が含まれ、ストリーム ヘッダー チャンク ('strh') とストリーム フォーマット チャンク ('strf') が必ず含まれる。
            // ストリーム ヘッダー チャンク ('strh') は、AVISTREAMHEADER 構造体で構成されている。
            // ストリーム フォーマット チャンク ('strf') は、ストリーム ヘッダー チャンクの後に続けて記述する必要がある。
            // ストリーム フォーマット チャンクは、ストリーム内のデータのフォーマットを記述する。このチャンクに含まれるデータは、ストリーム タイプによって異なる。
            // ビデオ ストリームの場合、この情報は必要に応じてパレット情報を含む BITMAPINFO 構造体である。オーディオ ストリームの場合、この情報は WAVEFORMATEX 構造体である。

            // Videoストリーム用の'strl'チャンク
            {
                var strl_list = hdrlList.CreateList("strl");
                {
                    var chunk = strl_list.CreateChunk("strh");
                    var strh  = new AVISTREAMHEADER();
                    strh.fccType               = ToFourCC("vids");
                    strh.fccHandler            = ToFourCC(fourCC);
                    strh.dwScale               = 1000 * 1000; // fps = dwRate / dwScale。秒間30フレームであることをあらわすのにdwScale=33333、dwRate=1000000という場合もあればdwScale=1、dwRate=30という場合もあります. For video streams, this is the frame rate.
                    strh.dwRate                = (int)(videoFormat.FramesPerSec * strh.dwScale);
                    strh.dwLength              = videoFrames;
                    strh.dwSuggestedBufferSize = 0x100000;
                    strh.dwQuality             = -1; // Quality is represented as a number between 0 and 10,000. If set to –1, drivers use the default quality value.

                    var data = StructureToBytes(strh);
                    chunk.Write(data);
                    chunk.Close();
                }
                {
                    var chunk = strl_list.CreateChunk("strf");
                    var strf  = new BITMAPINFOHEADER();
                    strf.biWidth       = videoFormat.Width;
                    strf.biHeight      = videoFormat.Height;
                    strf.biBitCount    = 24;
                    strf.biSizeImage   = strf.biHeight * ((3 * strf.biWidth + 3) / 4) * 4; // らしい
                    strf.biCompression = ToFourCC(fourCC);
                    strf.biSize        = System.Runtime.InteropServices.Marshal.SizeOf(strf);
                    strf.biPlanes      = 1;

                    var data = StructureToBytes(strf);
                    chunk.Write(data);
                    chunk.Close();
                }
                strl_list.Close();
            }

            // Audioストリーム用の'strl'チャンク(あれば)
            if (audioFormat != null)
            {
                var strl_list = hdrlList.CreateList("strl");
                {
                    var chunk = strl_list.CreateChunk("strh");
                    var strh  = new AVISTREAMHEADER();
                    strh.fccType               = ToFourCC("auds");
                    strh.fccHandler            = 0x00;                                                            // For audio and video streams, this specifies the codec for decoding the stream. pcmは不要。
                    strh.dwScale               = audioFormat.Channels;                                            // For audio streams, this rate corresponds to the time needed to play nBlockAlign bytes of audio, which for PCM audio is the just the sample rate.
                    strh.dwRate                = audioFormat.SamplesPerSec * strh.dwScale;                        // Dividing dwRate by dwScale gives the number of samples per second.
                    strh.dwSampleSize          = (short)(audioFormat.Channels * (audioFormat.BitsPerSample / 8)); // For audio streams, this number should be the same as the nBlockAlign member of the WAVEFORMATEX structure describing the audio.
                    strh.dwLength              = audioFrames;
                    strh.dwSuggestedBufferSize = strh.dwRate;                                                     // ?
                    strh.dwQuality             = -1;                                                              // Quality is represented as a number between 0 and 10,000. If set to –1, drivers use the default quality value.

                    var data = StructureToBytes(strh);
                    chunk.Write(data);
                    chunk.Close();
                }
                {
                    const int WAVE_FORMAT_PCM = 0x0001;
                    var       chunk           = strl_list.CreateChunk("strf");
                    var       strf            = new WAVEFORMATEX();
                    strf.nChannels       = audioFormat.Channels;
                    strf.wFormatTag      = WAVE_FORMAT_PCM;
                    strf.nSamplesPerSec  = audioFormat.SamplesPerSec;
                    strf.nBlockAlign     = (short)(audioFormat.Channels * (audioFormat.BitsPerSample / 8));
                    strf.nAvgBytesPerSec = strf.nSamplesPerSec * strf.nBlockAlign;
                    strf.wBitsPerSample  = audioFormat.BitsPerSample;
                    strf.cbSize          = 0;

                    var data = StructureToBytes(strf);
                    chunk.Write(data);
                    chunk.Close();
                }
                strl_list.Close();
            }
        }
 private static int GetTransfer(X264Profile inProfile, VideoFormat format)
 {
     int transfer = inProfile.Transfer;
     switch (format)
     {
         case VideoFormat.Videoformat480I:
         case VideoFormat.Videoformat480P:
             transfer = 7;
             break;
         case VideoFormat.Videoformat576I:
         case VideoFormat.Videoformat576P:
             transfer = 3;
             break;
         case VideoFormat.Videoformat720P:
         case VideoFormat.Videoformat1080I:
         case VideoFormat.Videoformat1080P:
             transfer = 1;
             break;
     }
     return transfer;
 }
Ejemplo n.º 47
0
        /// <summary>Create with video and audio stream.</summary>
        public AviWriter(System.IO.Stream outputAvi, string fourCC, VideoFormat videoFormat, AudioFormat audioFormat)
        {
            // RIFFファイルは、RIFFヘッダーとその後ろに続く 0個以上のリストとチャンクで構成されている。
            // RIFFヘッダーは、'RIFF'のFOURCC、4バイトのデータサイズ、データを識別するFOURCC、データから構成されている。
            // リストは、'LIST'のFOURCC、4バイトのデータサイズ、データを識別するFOURCC、データから構成されている。
            // チャンクは、データを識別するFOURCC、4バイトのデータサイズ、データから構成されている。
            // チャンクデータを識別するFOURCCは、2桁のストリーム番号とその後に続く2文字コード(dc=ビデオ,wb=音声,tx=字幕など)で構成されている。
            // AVIファイルは、'AVI 'のFOURCCと、2つの必須のLISTチャンク('hdrl''movi')、オプションのインデックスチャンクから構成されるRIFFファイルである。

            var riffFile = new RiffFile(outputAvi, "AVI ");

            // hdrlリストをとりあえずフレーム数=0で作成(あとで上書き)
            var hdrlList = riffFile.CreateList("hdrl");

            WriteHdrlList(hdrlList, fourCC, videoFormat, audioFormat, 0, 0);
            hdrlList.Close();

            // moviリストを作成し、AddImage/AddAudioごとにデータチャンクを追加
            var idx1List = new List <Idx1Entry>();
            var moviList = riffFile.CreateList("movi");

            this.AddImage += (data) =>
            {
                if (videoFormat == null)
                {
                    throw new InvalidOperationException("no video stream.");
                }
                var idx1 = WriteMoviList(moviList, "00dc", data);
                idx1List.Add(idx1);
            };

            this.AddAudio += (data) =>
            {
                if (audioFormat == null)
                {
                    throw new InvalidOperationException("no audio stream.");
                }
                var idx1 = WriteMoviList(moviList, "01wb", data);
                idx1List.Add(idx1);
            };

            // ファイルをクローズ
            this.Close += () =>
            {
                // moviリストを閉じる
                moviList.Close();

                // idx1チャンクを作成
                WriteIdx1Chunk(riffFile, idx1List);

                var videoFrames = idx1List.Where(x => x.ChunkId == "00dc").Count();
                var audioFrames = idx1List.Where(x => x.ChunkId == "01wb").Count();

                // hdrlListを正しいフレーム数で上書き
                var offset = hdrlList.Offset;
                riffFile.BaseStream.Seek(offset, System.IO.SeekOrigin.Begin);                        // hdrlリストの先頭まで戻る
                riffFile.BaseStream.Seek(12, System.IO.SeekOrigin.Current);                          // hdrlリストのヘッダ分飛ばす
                WriteHdrlList(riffFile, fourCC, videoFormat, audioFormat, videoFrames, audioFrames); // hdrlリストのデータを正しいフレーム数で上書き
                riffFile.BaseStream.Seek(0, System.IO.SeekOrigin.End);                               // 元の場所に戻る

                // ファイルをクローズ
                riffFile.Close();
                outputAvi.Dispose();
            };
        }
        private static bool GetFakeInterlaced(X264Profile inProfile, VideoFormat format, int fpsN, int fpsD)
        {
            bool fInterlaced = inProfile.UseFakeInterlaced;

            switch (format)
            {
                case VideoFormat.Videoformat480P:
                case VideoFormat.Videoformat576P:
                    fInterlaced = true;
                    break;
                case VideoFormat.Videoformat1080P:
                    if (((fpsN == 30000) && (fpsD == 1001)) || ((fpsN == 25000) && (fpsD == 1000))) // 29.976 or 25 fps
                        fInterlaced = true;
                    break;
            }

            return fInterlaced;
        }
 /// <summary>
 /// Helper function get id.
 /// </summary>
 /// <param name="videoFormat">Video format.</param>
 /// <returns>The <see cref="int"/> of the video format.</returns>
 public static int GetId(this VideoFormat videoFormat)
 {
     return($"{videoFormat.VideoColorFormat}{videoFormat.Width}{videoFormat.Height}".GetHashCode());
 }
 private static int GetColorprim(X264Profile inProfile, VideoFormat format)
 {
     int colorPrim = inProfile.ColorPrimaries;
     switch (format)
     {
         case VideoFormat.Videoformat480I:
         case VideoFormat.Videoformat480P:
             colorPrim = 4;
             break;
         case VideoFormat.Videoformat576I:
         case VideoFormat.Videoformat576P:
             colorPrim = 3;
             break;
         case VideoFormat.Videoformat720P:
         case VideoFormat.Videoformat1080I:
         case VideoFormat.Videoformat1080P:
             colorPrim = 1;
             break;
     }
     return colorPrim;
 }
Ejemplo n.º 51
0
        public void Start()
        {
            _run = true;

            g_Player.PlayBackEnded    += OnVideoEnded;
            g_Player.PlayBackStopped  += OnVideoStopped;
            g_Player.PlayBackStarted  += OnVideoStarted;
            g_Player.TVChannelChanged += OnTVChannelChanged;

            using (Settings reader = new MPSettings())
            {
                b3DMenuAlways = reader.GetValueAsBool("Auto3DPlugin", "3DMenuAlways", false);
                b3DMenuOnKey  = reader.GetValueAsBool("Auto3DPlugin", "3DMenuOnKey", false);
                String menuHotKey = reader.GetValueAsString("Auto3DPlugin", "3DMenuKey", "CTRL + D");

                if (menuHotKey.StartsWith("MCE")) // reject old configs
                {
                    menuHotKey = "";
                }

                if (menuHotKey.StartsWith("HID"))
                {
                    bMenuMCERemote = true;
                    mceRemoteKey   = menuHotKey;

                    HIDInput.getInstance().HidEvent += Auto3DSetup_HidEvent;
                }
                else
                {
                    bMenuHotKeyShift = menuHotKey.Contains("SHIFT");
                    bMenuHotKeyCtrl  = menuHotKey.Contains("CTRL");
                    bMenuHotKeyAlt   = menuHotKey.Contains("ALT");

                    if (menuHotKey.Contains("+"))
                    {
                        int pos = menuHotKey.LastIndexOf('+');
                        menuHotKey = menuHotKey.Substring(pos + 1).Trim();
                    }

                    _menuHotKey = (Keys)Enum.Parse(typeof(Keys), menuHotKey, true);
                }

                bCheckNameSimple = reader.GetValueAsBool("Auto3DPlugin", "CheckNameSimple", true);
                bCheckNameFull   = reader.GetValueAsBool("Auto3DPlugin", "CheckNameFull", true);

                bCheckSideBySide      = reader.GetValueAsBool("Auto3DPlugin", "SideBySide", true);
                bCheckTopAndBottom    = reader.GetValueAsBool("Auto3DPlugin", "TopAndBottom", false);
                bAnalyzeNetworkStream = reader.GetValueAsBool("Auto3DPlugin", "AnalyzeNetworkStream", true);

                String activeDeviceName = reader.GetValueAsString("Auto3DPlugin", "ActiveDevice", "");

                bTV    = reader.GetValueAsBool("Auto3DPlugin", "TV", false);
                bVideo = reader.GetValueAsBool("Auto3DPlugin", "Video", true);

                if (reader.GetValueAsBool("Auto3DPlugin", "CheckNameFormatSBS", true))
                {
                    _nameFormat = VideoFormat.Fmt3DSBS;
                }
                else
                {
                    _nameFormat = VideoFormat.Fmt3DTAB;
                }

                foreach (IAuto3D device in _listDevices)
                {
                    if (device.ToString() == activeDeviceName)
                    {
                        _activeDevice = device;
                    }
                }

                if (_activeDevice == null)
                {
                    _activeDevice = _listDevices[0];
                }

                Log.Info("Auto3D: Connecting to Device " + _activeDevice.ToString());

                _activeDevice.Start();

                if (_activeDevice is Auto3DUPnPBaseDevice)
                {
                    Auto3DUPnP.StartSSDP();
                }

                if (b3DMenuOnKey)
                {
                    Auto3DHelpers.GetMainForm().PreviewKeyDown += form_PreviewKeyDown;
                }

                GUIGraphicsContext.Render3DSubtitle         = reader.GetValueAsBool("Auto3DPlugin", "3DSubtitles", true);
                GUIGraphicsContext.Render3DSubtitleDistance = -reader.GetValueAsInt("Auto3DPlugin", "SubtitleDepth", 0);

                bConvert2Dto3DEnabled = reader.GetValueAsBool("Auto3DPlugin", "ConvertTo3D", false);
                GUIGraphicsContext.Convert2Dto3DSkewFactor = reader.GetValueAsInt("Auto3DPlugin", "SkewFactor", 10);

                bStretchSubtitles = reader.GetValueAsBool("Auto3DPlugin", "StretchSubtitles", false);

                bSuppressSwitchBackTo2D = reader.GetValueAsBool("Auto3DPlugin", "SupressSwitchBackTo2D", false);
                bConvert3DTo2D          = reader.GetValueAsBool("Auto3DPlugin", "Convert3DTo2D", false);

                SplitKeywords(ref _keywordsSBS, reader.GetValueAsString("Auto3DPlugin", "SwitchSBSLabels", "\"3DSBS\", \"3D SBS\""));
                SplitKeywords(ref _keywordsSBSR, reader.GetValueAsString("Auto3DPlugin", "SwitchSBSRLabels", "\"3DSBSR\", \"3D SBS R\""));
                SplitKeywords(ref _keywordsTAB, reader.GetValueAsString("Auto3DPlugin", "SwitchTABLabels", "\"3DTAB\", \"3D TAB\""));
                SplitKeywords(ref _keywordsTABR, reader.GetValueAsString("Auto3DPlugin", "SwitchTABRLabels", "\"3DTABR\", \"3D TAB R\""));

                bTurnDeviceOff     = reader.GetValueAsBool("Auto3DPlugin", "TurnDeviceOff", false);
                nTurnDeviceOffVia  = reader.GetValueAsInt("Auto3DPlugin", "TurnDeviceOffVia", 0);
                nTurnDeviceOffWhen = reader.GetValueAsInt("Auto3DPlugin", "TurnDeviceOffWhen", 0);

                bTurnDeviceOn     = reader.GetValueAsBool("Auto3DPlugin", "TurnDeviceOn", false);
                nTurnDeviceOnVia  = reader.GetValueAsInt("Auto3DPlugin", "TurnDeviceOnVia", 0);
                nTurnDeviceOnWhen = reader.GetValueAsInt("Auto3DPlugin", "TurnDeviceOnWhen", 0);
            }

            SystemEvents.PowerModeChanged  += SystemEvents_PowerModeChanged;
            SystemEvents.SessionEnding     += SystemEvents_SessionEnding;
            GUIGraphicsContext.OnNewAction += GUIGraphicsContext_OnNewAction;

            if (bTurnDeviceOff && (nTurnDeviceOnWhen == 0 || nTurnDeviceOnWhen == 2) && _activeDevice.GetTurnOffInterfaces() != DeviceInterface.None)
            {
                _activeDevice.TurnOn((DeviceInterface)nTurnDeviceOnVia);
            }
        }
Ejemplo n.º 52
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="source"></param>
 public ExternalPlayer(string mediaPath, VideoFormat videoFormat)
 {
     _videoFormat = videoFormat;
     _mediaPath   = mediaPath;
 }
Ejemplo n.º 53
0
        private void Analyze3DFormatVideo(g_Player.MediaType type)
        {
            lock (this)
            {
                if (type == g_Player.MediaType.TV)
                {
                    Thread.Sleep(500); // wait 500ms to get a valid channel name

                    String channel = GUIPropertyManager.GetProperty("#TV.View.channel");

                    if (channel == _currentName)
                    {
                        return;
                    }

                    _currentName = channel;
                }

                _bPlaying = false;

                // wait for ending worker thread

                if (_workerThread != null && _workerThread.IsAlive)
                {
                    Thread.Sleep(20);
                }

                // is 3d mode is active switch back to normal mode

                if (_currentMode != VideoFormat.Fmt2D)
                {
                    SwitchBack();
                }

                if ((type == g_Player.MediaType.Video && bVideo) || (type == g_Player.MediaType.TV && bTV))
                {
                    _bPlaying = true;

                    if (!b3DMenuAlways)
                    {
                        Log.Info("Auto3D: Automatic Mode");

                        if (bCheckNameFull)
                        {
                            var matchedKeywords = new Dictionary <string, MatchingVideoFormat>();
                            foreach (var keyword in _keywordsSBSR)
                            {
                                Log.Debug("Auto3D: Check if name contains \"" + keyword + "\"");

                                if (_currentName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    matchedKeywords.Add(keyword, MatchingVideoFormat.SydeBySide3DReverse);
                                }
                            }

                            foreach (var keyword in _keywordsSBS)
                            {
                                Log.Debug("Auto3D: Check if name contains \"" + keyword + "\"");

                                if (_currentName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    matchedKeywords.Add(keyword, MatchingVideoFormat.SydeBySide3D);
                                }
                            }

                            foreach (var keyword in _keywordsTABR)
                            {
                                Log.Debug("Auto3D: Check if name contains \"" + keyword + "\"");

                                if (_currentName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    matchedKeywords.Add(keyword, MatchingVideoFormat.TopBottom3DReverse);
                                }
                            }

                            foreach (var keyword in _keywordsTAB)
                            {
                                Log.Debug("Auto3D: Check if name contains \"" + keyword + "\"");

                                if (_currentName.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    matchedKeywords.Add(keyword, MatchingVideoFormat.TopBottom3D);
                                }
                            }

                            if (matchedKeywords.Any())
                            {
                                Log.Info("Auto3D: Name contains \"{0}\"", string.Join("\", \"", matchedKeywords.Keys));

                                var keyword        = matchedKeywords.Keys.OrderByDescending(x => x).FirstOrDefault();
                                var detectedFormat = MatchingVideoFormat.Simple2D;
                                if (!string.IsNullOrEmpty(keyword))
                                {
                                    if (!matchedKeywords.TryGetValue(keyword, out detectedFormat))
                                    {
                                        Log.Info("Auto3D: not matched key for keyword \"{0}\" and 3D format is going to default {1}", keyword, detectedFormat);
                                        detectedFormat = MatchingVideoFormat.Simple2D;
                                    }
                                    else
                                    {
                                        Log.Info("Auto3D: most matched is \"{0}\" and 3D format is {1}", keyword, detectedFormat);
                                    }
                                }
                                else
                                {
                                    Log.Info("Auto3D: key is empty and 3D format is going to default {0}", detectedFormat);
                                }

                                var format = ConvertMatchingFormatToVideoFormat(detectedFormat);
                                if (_activeDevice.SwitchFormat(_currentMode, format))
                                {
                                    GUIGraphicsContext.Render3DMode  = format == VideoFormat.Fmt3DSBS ? GUIGraphicsContext.eRender3DMode.SideBySide : GUIGraphicsContext.eRender3DMode.TopAndBottom;
                                    GUIGraphicsContext.Switch3DSides = detectedFormat.HasFlag(MatchingVideoFormat.Reverse);
                                    _currentMode = format;
                                    UpdateSubtitleRenderFormat();
                                    return;
                                }
                            }
                        }

                        if (_currentMode == VideoFormat.Fmt2D && bCheckNameSimple)
                        {
                            if (_currentName.ToUpper().Contains("3D"))
                            {
                                Log.Info("Auto3D: Name contains \"3D\"");

                                if (_activeDevice.SwitchFormat(_currentMode, _nameFormat))
                                {
                                    switch (_nameFormat)
                                    {
                                    case VideoFormat.Fmt3DSBS:

                                        GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.SideBySide;
                                        break;

                                    case VideoFormat.Fmt3DTAB:

                                        GUIGraphicsContext.Render3DMode = GUIGraphicsContext.eRender3DMode.TopAndBottom;
                                        break;
                                    }

                                    _currentMode = _nameFormat;
                                    UpdateSubtitleRenderFormat();
                                }

                                return;
                            }
                        }
                    }
                    else // b3DMenuAlways
                    {
                        Log.Info("Auto3D: Manual Mode");

                        ManualSelect3DFormat(VideoFormat.Fmt2D);
                        UpdateSubtitleRenderFormat();
                        return;
                    }

                    if ((bCheckSideBySide || bCheckTopAndBottom) /* && type == g_Player.MediaType.Video*/)
                    {
                        AnalyzeVideo();
                    }
                }
            }
        }
Ejemplo n.º 54
0
 public void SetVideoSinkFormat(VideoFormat videoFormat) => _formatManager.SetSelectedFormat(videoFormat);
Ejemplo n.º 55
0
 public RtpVideoSink(VideoFormat format)
     : base(format)
 {
     _Writer = new RtpWriter(format.ClockRate);
 }
Ejemplo n.º 56
0
 public void GotVideoFrame(IPEndPoint remoteEndPoint, uint timestamp, byte[] frame, VideoFormat format)
 {
     if (OnVideoSinkDecodedSample != null)
     {
         try
         {
             foreach (var decoded in _videoDecoder.DecodeVideo(frame, VideoPixelFormatsEnum.Bgr, format.Codec))
             {
                 OnVideoSinkDecodedSample(decoded.Sample, decoded.Width, decoded.Height, (int)(decoded.Width * 3), VideoPixelFormatsEnum.Bgr);
             }
         }
         catch (Exception excp)
         {
             Console.WriteLine($"Exception decoding video. {excp.Message}");
         }
     }
 }
Ejemplo n.º 57
0
        private void button1_Click(object sender, EventArgs e)
        {
            ClientFlag flags = ttclient.GetFlags();

            //Audio-tab
            if ((ttclient.Flags & ClientFlag.CLIENT_SNDINOUTPUT_DUPLEX) ==
                ClientFlag.CLIENT_SNDINOUTPUT_DUPLEX)
            {
                ttclient.CloseSoundDuplexDevices();
            }
            else
            {
                ttclient.CloseSoundInputDevice();
                ttclient.CloseSoundOutputDevice();
            }

            ItemData inputItem  = (ItemData)sndinputComboBox.SelectedItem;
            ItemData outputItem = (ItemData)sndoutputComboBox.SelectedItem;

            settings.sndinputid  = inputItem.id;
            settings.sndoutputid = outputItem.id;

            if (duplexCheckBox.Checked)
            {
                if (!ttclient.InitSoundDuplexDevices(settings.sndinputid, settings.sndoutputid))
                {
                    MessageBox.Show("Failed to init sound devices");
                }

                SpeexDSP spxdsp = new SpeexDSP(false);
                ttclient.GetSoundInputPreprocess(ref spxdsp);
                spxdsp.nEchoSuppress           = SpeexDSPConstants.DEFAULT_ECHO_SUPPRESS;
                spxdsp.nEchoSuppressActive     = SpeexDSPConstants.DEFAULT_ECHO_SUPPRESS_ACTIVE;
                spxdsp.bEnableEchoCancellation = echocancelCheckBox.Checked;
                ttclient.SetSoundInputPreprocess(spxdsp);
            }
            else
            {
                if (!ttclient.InitSoundInputDevice(settings.sndinputid))
                {
                    MessageBox.Show("Failed to init sound input device");
                }

                if (!ttclient.InitSoundOutputDevice(settings.sndoutputid))
                {
                    MessageBox.Show("Failed to init sound output device");
                }
            }

            if (wasapiRadioButton.Checked)
            {
                settings.soundsystem = SoundSystem.SOUNDSYSTEM_WASAPI;
            }
            else if (dsoundRadioButton.Checked)
            {
                settings.soundsystem = SoundSystem.SOUNDSYSTEM_DSOUND;
            }
            else if (winmmRadioButton.Checked)
            {
                settings.soundsystem = SoundSystem.SOUNDSYSTEM_WINMM;
            }

            //Video-tab
            if (viddevComboBox.Items.Count > 0)
            {
                VideoCodec codec = new VideoCodec();
                codec.nCodec = Codec.WEBM_VP8_CODEC;
                codec.webm_vp8.nRcTargetBitrate = (int)vidbitrateNumericUpDown.Value;
                codec.webm_vp8.nEncodeDeadline  = WebMVP8CodecConstants.WEBM_VPX_DL_REALTIME;

                VideoFormat capformat = videodevs[viddevComboBox.SelectedIndex].videoFormats[formatComboBox.SelectedIndex];

                if (ttclient.Flags.HasFlag(ClientFlag.CLIENT_VIDEOCAPTURE_READY) &&
                    !(settings.videoid == videodevs[viddevComboBox.SelectedIndex].szDeviceID &&
                      Util.Equals(codec, settings.codec) &&
                      Util.Equals(capformat, settings.capformat)))
                {
                    ttclient.CloseVideoCaptureDevice();
                }

                settings.codec.nCodec = Codec.WEBM_VP8_CODEC;
                settings.codec.webm_vp8.nRcTargetBitrate = (int)vidbitrateNumericUpDown.Value;

                settings.videoid   = videodevs[viddevComboBox.SelectedIndex].szDeviceID;
                settings.capformat = capformat;
                if (!ttclient.Flags.HasFlag(ClientFlag.CLIENT_VIDEOCAPTURE_READY))
                {
                    if (!ttclient.InitVideoCaptureDevice(settings.videoid, settings.capformat))
                    {
                        MessageBox.Show("Failed to initialize video capture device");
                    }
                }
            }

            //Advanced-tab
            if (fwCheckBox.Checked != WindowsFirewall.AppExceptionExists(Application.ExecutablePath))
            {
                if (fwCheckBox.Checked)
                {
                    WindowsFirewall.AddAppException(Application.ProductName, Application.ExecutablePath);
                }
                else
                {
                    WindowsFirewall.RemoveAppException(Application.ExecutablePath);
                }
            }
        }
Ejemplo n.º 58
0
//        private void DownloadThread ()
//        {
//        	
//        }
        
        private Exception SetupDownload (Video video, MainProgramElements mainWindow)
        {
        	try
        	{
        		IEnumerable<YouTubeVideo> videos = new List<YouTubeVideo>();
        		using(var service = Client.For(YouTube.Default))
        		{
        			videos = service.GetAllVideos(video.Location);
        		}
        		
	        	YouTubeVideo currentVideo = default(YouTubeVideo);
	        	
	        	if(video.IsAudioFile || video.VideoFormat != VideoFormat.Mp4 || (!video.IsAudioFile && video.VideoFormat == VideoFormat.Mp4 && video.Quality == 360))
	        	{
	        		currentVideo = videos.FirstOrDefault(info => !video.IsAudioFile ? (info.Format == video.VideoFormat && info.Resolution == video.Quality) : (video.AudioFormat == AudioFormat.Mp3 && info.AudioFormat == video.AudioFormat && info.AudioBitrate == video.Quality));
	        	}
	        		
	        	if (currentVideo != default(YouTubeVideo))
	            {
	        		mainWindow.CurrentDownloadOutputText = string.Format(CultureInfo.InstalledUICulture, "Downloading (#{0}/{1}) '{2}' at {3}{4}", video.Position, mainWindow.Videos.Count(), currentVideo.FullName.Truncate(56), !video.IsAudioFile ? currentVideo.Resolution : currentVideo.AudioBitrate, !video.IsAudioFile ? "p resolution" : " bitrate");
					
	        		this.Downloader(currentVideo, mainWindow, video.IsAudioFile);
	        		
	        		return null;
	            } 
	            else
	            {      	
	                var formatsEstablished = new List<VideoFormat> ();
	                var qualitiesEstablished = new List<int> ();
	                using (StreamWriter outfile = new StreamWriter ("Acceptable Options.txt"))
	                {
	                    outfile.Write(string.Format(CultureInfo.CurrentCulture, "This file will show you all formats available for the current URL, as well as the resolutions that are acceptable for that URL.\n\n{0}:\n\nVideo Formats:\n", video.Location));
	                    for (var position = videos.Where(info => info.Format != VideoFormat.Unknown && formatsEstablished.All(format => info.Format != format)).Select(info => info.VideoType).GetEnumerator(); position.MoveNext();)
	                    {
	                        VideoFormat format = position.Current;
	                        formatsEstablished.Add(format);
	                        switch (format)
	                        {
	                            case VideoFormat.Mp4:
	                                outfile.Write(string.Format(CultureInfo.CurrentCulture, "Format: {0} | Resolution: {1}p\n", format, "360"));
	                                break;
	                            default:
	                                var validVideos = videoInfos.Where(videoInfo => (videoInfo.Resolution >= UrlShaping.MinimumQuality[typeof(VideoType)] && videoInfo.Resolution <= UrlShaping.MaximumQuality) && videoInfo.VideoType.Equals(format) && qualitiesEstablished.All(quality => videoInfo.Resolution != quality)).Select(videoInfo => videoInfo.Resolution);
									foreach (int currentResolution in validVideos)
									{
										outfile.Write(string.Format(CultureInfo.CurrentCulture, "Format: {0} | Resolution: {1}p\n", format, currentResolution));
									}
	                                break;
	                        }
	                        qualitiesEstablished.Clear();
	                    }
	                    
	                    outfile.Write("\nAudio Formats:\n");
	                    var audioQualitiesEstablished = new List<AudioType> ();
	                    
	                    for (var position = videoInfos.Where(info => info.AudioType != AudioType.Unknown && audioQualitiesEstablished.All(quality => info.AudioType != quality)).Select(info => info.AudioType).GetEnumerator(); position.MoveNext();)
	                    {
	                        AudioType format = position.Current;
	                        audioQualitiesEstablished.Add(format);
							var validAudioTracks = videoInfos.Where(videoInfo => (videoInfo.AudioBitrate >= UrlShaping.MinimumQuality[typeof(AudioType)] && videoInfo.AudioBitrate <= UrlShaping.MaximumQuality) && videoInfo.AudioType.Equals(format)).Select(videoInfo => videoInfo.AudioBitrate);
							foreach (int currentQuality in validAudioTracks)
							{
								outfile.Write(string.Format(CultureInfo.CurrentCulture, "Format: {0} | Bitrate: {1}\n", format, currentQuality));
							}
	                        qualitiesEstablished.Clear();
	                    }
	                }
	                throw new NotSupportedException ("An acceptable options file has been exported to the program's root folder. Check there for more information.");
	            }
        	}
        	catch (Exception ex) { return ex; }
        }
Ejemplo n.º 59
0
 public bool Transcode(TranscodeInfo info, VideoFormat format, Quality quality, Standard standard)
 {
     try
     {
         if (!Supports(format))
         {
             return(false);
         }
         string ext = System.IO.Path.GetExtension(info.file);
         if (ext.ToLower() != ".dvr-ms" && ext.ToLower() != ".sbe")
         {
             Log.Info("DVRMS2WMV: wrong file format");
             return(false);
         }
         Log.Info("DVRMS2WMV: create graph");
         graphBuilder = (IGraphBuilder) new FilterGraph();
         _rotEntry    = new DsROTEntry((IFilterGraph)graphBuilder);
         Log.Info("DVRMS2WMV: add streambuffersource");
         bufferSource = (IStreamBufferSource) new StreamBufferSource();
         IBaseFilter filter = (IBaseFilter)bufferSource;
         graphBuilder.AddFilter(filter, "SBE SOURCE");
         Log.Info("DVRMS2WMV: load file:{0}", info.file);
         IFileSourceFilter fileSource = (IFileSourceFilter)bufferSource;
         int hr = fileSource.Load(info.file, null);
         //add mpeg2 audio/video codecs
         string strVideoCodec = "";
         string strAudioCodec = "";
         using (MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.MPSettings())
         {
             strVideoCodec = xmlreader.GetValueAsString("mytv", "videocodec", "MPC - MPEG-2 Video Decoder (Gabest)");
             strAudioCodec = xmlreader.GetValueAsString("mytv", "audiocodec", "MPC - MPA Decoder Filter");
         }
         Log.Info("DVRMS2WMV: add mpeg2 video codec:{0}", strVideoCodec);
         Mpeg2VideoCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strVideoCodec);
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:Add mpeg2 video  to filtergraph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         Log.Info("DVRMS2WMV: add mpeg2 audio codec:{0}", strAudioCodec);
         Mpeg2AudioCodec = DirectShowUtil.AddFilterToGraph(graphBuilder, strAudioCodec);
         if (Mpeg2AudioCodec == null)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to add mpeg2 audio codec");
             Cleanup();
             return(false);
         }
         Log.Info("DVRMS2WMV: connect streambufer source->mpeg audio/video decoders");
         //connect output #0 of streambuffer source->mpeg2 audio codec pin 1
         //connect output #1 of streambuffer source->mpeg2 video codec pin 1
         IPin pinOut0, pinOut1;
         IPin pinIn0, pinIn1;
         pinOut0 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 0); //audio
         pinOut1 = DsFindPin.ByDirection((IBaseFilter)bufferSource, PinDirection.Output, 1); //video
         if (pinOut0 == null || pinOut1 == null)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to get pins of source");
             Cleanup();
             return(false);
         }
         pinIn0 = DsFindPin.ByDirection(Mpeg2VideoCodec, PinDirection.Input, 0); //video
         pinIn1 = DsFindPin.ByDirection(Mpeg2AudioCodec, PinDirection.Input, 0); //audio
         if (pinIn0 == null || pinIn1 == null)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to get pins of mpeg2 video/audio codec");
             Cleanup();
             return(false);
         }
         hr = graphBuilder.Connect(pinOut0, pinIn1);
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to connect audio pins :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         hr = graphBuilder.Connect(pinOut1, pinIn0);
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to connect video pins :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         string outputFilename = System.IO.Path.ChangeExtension(info.file, ".wmv");
         if (!AddWmAsfWriter(outputFilename, quality, standard))
         {
             return(false);
         }
         Log.Info("DVRMS2WMV: start pre-run");
         mediaControl = graphBuilder as IMediaControl;
         mediaSeeking = bufferSource as IStreamBufferMediaSeeking;
         mediaEvt     = graphBuilder as IMediaEventEx;
         mediaPos     = graphBuilder as IMediaPosition;
         //get file duration
         long lTime = 5 * 60 * 60;
         lTime *= 10000000;
         long pStop = 0;
         hr = mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                        AMSeekingSeekingFlags.NoPositioning);
         if (hr == 0)
         {
             long lStreamPos;
             mediaSeeking.GetCurrentPosition(out lStreamPos); // stream position
             m_dDuration = lStreamPos;
             lTime       = 0;
             mediaSeeking.SetPositions(new DsLong(lTime), AMSeekingSeekingFlags.AbsolutePositioning, new DsLong(pStop),
                                       AMSeekingSeekingFlags.NoPositioning);
         }
         double duration = m_dDuration / 10000000d;
         Log.Info("DVRMS2WMV: movie duration:{0}", Util.Utils.SecondsToHMSString((int)duration));
         hr = mediaControl.Run();
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
         int maxCount = 20;
         while (true)
         {
             long lCurrent;
             mediaSeeking.GetCurrentPosition(out lCurrent);
             double dpos = (double)lCurrent;
             dpos /= 10000000d;
             System.Threading.Thread.Sleep(100);
             if (dpos >= 2.0d)
             {
                 break;
             }
             maxCount--;
             if (maxCount <= 0)
             {
                 break;
             }
         }
         Log.Info("DVRMS2WMV: pre-run done");
         Log.Info("DVRMS2WMV: Get duration of movie");
         mediaControl.Stop();
         FilterState state;
         mediaControl.GetState(500, out state);
         GC.Collect();
         GC.Collect();
         GC.Collect();
         GC.WaitForPendingFinalizers();
         Log.Info("DVRMS2WMV: reconnect mpeg2 video codec->ASF WM Writer");
         graphBuilder.RemoveFilter(fileWriterbase);
         if (!AddWmAsfWriter(outputFilename, quality, standard))
         {
             return(false);
         }
         Log.Info("DVRMS2WMV: Start transcoding");
         hr = mediaControl.Run();
         if (hr != 0)
         {
             Log.Error("DVRMS2WMV:FAILED:unable to start graph :0x{0:X}", hr);
             Cleanup();
             return(false);
         }
     }
     catch (Exception e)
     {
         // TODO: Handle exceptions.
         Log.Error("unable to transcode file:{0} message:{1}", info.file, e.Message);
         return(false);
     }
     return(true);
 }
        private static bool GetPicStruct(X264Profile inProfile, VideoFormat format)
        {
            bool pStruct = inProfile.UseForcePicStruct;

            switch (format)
            {
                case VideoFormat.Videoformat576P:
                    pStruct = true;
                    break;
            }

            return pStruct;
        }