コード例 #1
2
ファイル: Crop.cs プロジェクト: gogosub77/Kanae
        public async Task<ValidationResult> Execute(MediaInfo mediaInfo, Int32 x, Int32 y, Int32 width, Int32 height)
        {
            if (x < 0 || y < 0 || width <= 0 || height <= 0)
            {
                return new ValidationResult("サイズの指定が不正です。");
            }

            var mediaContent = await _mediaRepository.Get(mediaInfo);
            if (mediaContent == null)
            {
                return new ValidationResult("指定されたメディアが見つかりませんでした。");
            }

            var data = await mediaContent.GetContentAsync();
            var imageInfo = new MagickImageInfo(data);
            if (imageInfo.Width < (x + width) || imageInfo.Height < (y + height))
            {
                return new ValidationResult("指定されたサイズは画像のサイズを超えています。");
            }

            // リサイズするよ!
            using (var image = new MagickImage(data))
            {
                image.Crop(new MagickGeometry(x, y, width, height));
                image.Page = new MagickGeometry(0, 0, width, height);
                
                // そして更新
                await _mediaRepository.Update(mediaInfo, image.ToByteArray());
            }

            return ValidationResult.Success;
        }
コード例 #2
1
ファイル: Job.cs プロジェクト: inSight-mk1/ExpertVideoToolbox
        private void runTask(videoTask t, Process process)
        {
            this.rsForm.setPercent("0.0");
            this.rsForm.setTime("");
            this.rsForm.setFps("");
            this.rsForm.setEta("");

            string fp = t.getFP();

            process = new System.Diagnostics.Process();

            process.StartInfo.FileName = "cmd";

            // 必须禁用操作系统外壳程序
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput  = true;

            process.ErrorDataReceived  += new DataReceivedEventHandler(OutputHandler);
            process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);

            process.Start();

            this.PIDs[0]    = process.Id;
            this.rsForm.PID = process.Id;
            this.rsForm.setStopBtnState(true);

            // 找到预设存储的文件并提取到taskSetting中
            string      tsfp = System.Windows.Forms.Application.StartupPath + "\\taskSettings\\" + t.getSetting() + ".json";
            taskSetting ts   = JsonConvert.DeserializeObject <taskSetting>(File.ReadAllText(tsfp));

            // 将encoder信息传给信息显示界面
            this.rsForm.encodingProgram = ts.encoder;
            this.rsForm.HideVideoEncoderSetting();

            cmdCode c = new cmdCode(fp, ts, this.outputFolderPath);
            string  cmd;

            int type     = c.taskType();
            int checkNum = 0;

            int       beforeProcessCheckTime = 3500;
            int       processCheckInterval   = 1000;
            const int checkF = 20;

            // 定义一个内部(匿名)方法
            // 整个视频转换过程结束时
            InnerMethodDelagate afterSuccess = delegate()
            {
                this.finishedNum++;
                this.rsForm.setStatusBarFilesCountLabel(this.finishedNum, this.num);

                try
                {
                    process.CancelErrorRead();
                    process.CancelOutputRead();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                this.rsForm.setEta("");
                this.rsForm.setFps("");
                this.rsForm.setTime("");
                this.rsForm.setEstKbps("");
                this.rsForm.SetTaskStepsLabel(true);

                Process p = Process.GetProcessById(this.PIDs[0]);
                p.Kill();
                this.rsForm.setStopBtnState(false);
                this.rsForm.setPercent("-3");
                this.isfinished[0] = true;
                this.reportCount   = 0;
                this.log.Clear();

                miniLog += t.getFP() + Environment.NewLine + Environment.NewLine + Environment.NewLine;
                saveMiniLog2File();
            };

            // 运行失败时调用
            InnerMethodDelagate afterFailed = delegate()
            {
                this.isfailed = true;

                saveLog2File();

                this.rsForm.setPercent("-1");
                this.rsForm.setTime("发生错误");
                this.rsForm.setFps("日志保存在程序目录");

                int sleepTime = 5;  // 设置失败后继续下一个任务的时间
                this.rsForm.setEta(sleepTime.ToString() + "秒后继续运行");

                this.rsForm.setStatusBarLabelTextColorRED();
                this.finishedNum++;
                this.rsForm.setStatusBarFilesCountLabel(this.finishedNum, this.num);
                this.rsForm.HideVideoEncoderSetting();

                try
                {
                    process.CancelErrorRead();
                    process.CancelOutputRead();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                Thread.Sleep(sleepTime * 1000);

                Process p = Process.GetProcessById(this.PIDs[0]);
                p.Kill();
                this.rsForm.setStopBtnState(false);
                this.rsForm.setPercent("-3");
                this.isfinished[0] = true;
                this.reportCount   = 0;
                this.log.Clear();
            };

            // 视频编码前更新UI(显示视频总帧数)
            InnerMethodDelagate DispVideoFrames = delegate()
            {
                // MediaInfo读取视频帧数
                MediaInfo MI = new MediaInfo();
                string    duration;
                string    frameRate;
                string    frames;
                MI.Open(t.getFP());
                duration = MI.Get(StreamKind.Video, 0, "Duration");
                try
                {
                    double totalTime = Double.Parse(duration) / 1000.0;
                    frameRate = MI.Get(StreamKind.Video, 0, "FrameRate");
                    frames    = ((int)(totalTime * Double.Parse(frameRate))).ToString();

                    if (!String.IsNullOrWhiteSpace(frames))
                    {
                        this.rsForm.setTime("0/" + frames);
                    }
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }
            };

            InnerMethodDelagate VideoEncode = delegate()
            {
                // 视频编码
                this.encoding = true;
                this.rsForm.setPercent("0.0");

                string ext = this.getFileExtName(t.getFP());
                if (String.Equals(ext, "avs", StringComparison.CurrentCultureIgnoreCase))
                {
                    this.videoType = AVS;
                }
                else
                {
                    this.videoType = NORMAL;
                    DispVideoFrames();
                }

                cmd = c.cmdCodeGenerate(VIDEOENCODE, this.videoType);
                process.StandardInput.WriteLine(cmd);

                try
                {
                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                checkNum         = 0;
                this.reportCount = 0;
                int cpx2 = this.checkPattern + this.checkPattern;
                for (int i = 0; i < cpx2; i++)
                {
                    checkFrame[i] = 0;
                }
                for (int i = 0; i < cpx2; i++)
                {
                    this.fps[i] = 0;
                }

                Thread.Sleep(beforeProcessCheckTime);

                Process p;
                switch (videoType)
                {
                case NORMAL:
                    p = GetSubTaskProcess(ts.encoder);
                    if (p != null)
                    {
                        this.subTaskPID = p.Id;
                    }
                    else
                    {
                        this.subTaskPID = -1;
                    }
                    break;

                case AVS:
                    Process avsP  = GetSubTaskProcess("avs4x265.exe");
                    int     avsId = avsP.Id;
                    if (avsP != null)
                    {
                        bool hasFound = false;

                        // 等待视频编码进程启动,最长等待1小时
                        for (int i = 0; i < 7200; i++)
                        {
                            // 确认avs进程仍在运行
                            try
                            {
                                Process.GetProcessById(avsId);
                            }
                            catch (Exception e)
                            {
                                if (this.encoding == true || ConfirmFailed())
                                {
                                    afterFailed();
                                }
                                return;
                            }

                            // 每隔500ms寻找视频编码进程
                            p = GetSubTaskProcess(ts.encoder, avsId);
                            if (p != null)
                            {
                                this.subTaskPID = p.Id;
                                hasFound        = true;
                                break;
                            }
                            else
                            {
                                Thread.Sleep(500);
                            }
                        }

                        if (!hasFound)
                        {
                            this.subTaskPID = -1;
                        }
                    }
                    else
                    {
                        this.subTaskPID = -1;
                    }
                    break;

                default:
                    break;
                }

                this.rsForm.ShowVideoEncoderSetting();

                while (this.encoding == true || this.postProcessing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        if (this.encoding == true || ConfirmFailed())
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                }
                try
                {
                    process.CancelErrorRead();
                    process.CancelOutputRead();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                this.rsForm.HideVideoEncoderSetting();
            };

            InnerMethodDelagate Mux = delegate()
            {
                // muxer
                this.muxing = true;
                int stepIdx = type == ONLYVIDEO ? 2 : 3;
                this.rsForm.SetTaskStepsLabel(false, stepIdx, stepIdx, MUXER);

                cmd = c.cmdCodeGenerate(MUXER);
                process.StandardInput.WriteLine(cmd);

                try
                {
                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();
                }
                catch (Exception e)
                {
                    //saveLog2File();
                }

                checkNum = 0;

                Thread.Sleep(beforeProcessCheckTime);  // 有些超短的视频(1-2M),如果不加这句就会直接判定为任务已失败,疑似原因:没等判断完进程就已经结束

                string muxerProcessName = "";
                if (String.Equals("mp4", ts.outputFormat))
                {
                    muxerProcessName = "mp4Box";
                }
                else if (String.Equals("mkv", ts.outputFormat))
                {
                    muxerProcessName = "mkvmerge";
                }

                Process p = GetSubTaskProcess(muxerProcessName);
                if (p != null)
                {
                    this.subTaskPID = p.Id;
                }
                else
                {
                    this.subTaskPID = -1;
                }

                while (this.muxing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                        if (this.muxing == true)
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                    //checkNum = checkCmdRunning(checkNum, checkF);
                    //if (checkNum == -1)
                    //{
                    //    return;
                    //}
                }

                afterSuccess();

                string tempVideoFp = c.cmdCodeGenerate(DELETEVIDEOTEMP);
                string tempAudioFp = c.cmdCodeGenerate(DELETEAUDIOTEMP);
                try
                {
                    File.Delete(tempVideoFp);
                    File.Delete(tempAudioFp);
                }
                catch (System.IO.IOException ex)
                {
                    this.log.AppendLine("出现异常:" + ex);
                    saveLog2File();
                }
            };

            // 音频编码或复制开始前更新UI(显示音频总时长)
            InnerMethodDelagate DispAudioDuration = delegate()
            {
                // MediaInfo读取音频时长
                MediaInfo MI = new MediaInfo();
                string    duration;
                MI.Open(c.getAudioSource());
                duration = MI.Get(StreamKind.Audio, 0, 69);

                if (!String.IsNullOrWhiteSpace(duration))
                {
                    this.rsForm.setTime("0/" + duration);
                }

                this.rsForm.setPercent("0.0", AUDIOENCODE);
            };

            InnerMethodDelagate ClearUIAfterAudioProcessing = delegate()
            {
                this.rsForm.setPercent("0.0");
                this.rsForm.setTime("");
                this.rsForm.setFps("");
            };

            switch (type)
            {
            case ONLYVIDEO:

                this.rsForm.SetTaskStepsLabel(false, 1, 2, VIDEOENCODE);

                VideoEncode();

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                //afterSuccess();

                Mux();

                break;

            case COPYAUDIO:
                // 复制音频
                cmd = c.cmdCodeGenerate(AUDIOCOPY);
                process.StandardInput.WriteLine(cmd);
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
                this.audioProcessing = true;
                this.rsForm.SetTaskStepsLabel(false, 1, 3, AUDIOCOPY);
                DispAudioDuration();

                checkNum = 0;

                Thread.Sleep(beforeProcessCheckTime);

                Process p = GetSubTaskProcess("ffmpeg");
                if (p != null)
                {
                    this.subTaskPID = p.Id;
                }
                else
                {
                    this.subTaskPID = -1;
                }

                while (this.audioProcessing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                        if (this.audioProcessing == true)
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                    //checkNum = checkCmdRunning(checkNum, checkF);
                    //if (checkNum == -1)
                    //{
                    //    return;
                    //}
                }
                ClearUIAfterAudioProcessing();

                process.CancelErrorRead();
                process.CancelOutputRead();

                this.rsForm.SetTaskStepsLabel(false, 2, 3, VIDEOENCODE);

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                VideoEncode();

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                Mux();

                break;

            case SUPPRESSAUDIO:
                // 音频编码
                cmd = c.cmdCodeGenerate(AUDIOENCODE);
                process.StandardInput.WriteLine(cmd);
                process.BeginErrorReadLine();
                process.BeginOutputReadLine();
                this.audioProcessing = true;
                this.rsForm.SetTaskStepsLabel(false, 1, 3, AUDIOENCODE);
                DispAudioDuration();

                checkNum = 0;

                Thread.Sleep(beforeProcessCheckTime);

                Process p2 = GetSubTaskProcess(ts.audioEncoder);
                if (p2 != null)
                {
                    this.subTaskPID = p2.Id;
                }
                else
                {
                    this.subTaskPID = -1;
                }

                while (this.audioProcessing == true)
                {
                    try
                    {
                        Process.GetProcessById(this.subTaskPID);
                    }
                    catch (Exception e)
                    {
                        Thread.Sleep(1000);
                        if (this.audioProcessing == true)
                        {
                            afterFailed();
                        }
                        return;
                    }

                    Thread.Sleep(processCheckInterval);
                    //checkNum = checkCmdRunning(checkNum, checkF);
                    //if (checkNum == -1)
                    //{
                    //    return;
                    //}
                }
                ClearUIAfterAudioProcessing();

                process.CancelErrorRead();
                process.CancelOutputRead();

                this.rsForm.SetTaskStepsLabel(false, 2, 3, VIDEOENCODE);

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                VideoEncode();

                // 一个子任务失败了意味着这个文件的编码任务失败,所以在所有子任务开始时都要检查checkNum是否为-1
                if (isfailed)
                {
                    return;
                }
                Mux();

                break;

            default:
                cmd = "";
                break;
            }

            //MessageBox.Show(cmd);
        }
コード例 #3
0
ファイル: MainWindow.cs プロジェクト: Bram77/xbmcontrol-evo
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        oXbmc = new XBMC_Communicator();
        oXbmc.SetIp("10.0.0.5");
        oXbmc.SetConnectionTimeout(4000);
        oXbmc.SetCredentials("", "");
        oXbmc.Status.StartHeartBeat();

        Build ();

        this.AllowStaticAccess();

        //Create objects used
        oPlaylist 		= new Playlist(this);
        oControls		= new Controls(this);
        oMenuItems		= new MenuItems(this);
        oContextMenu 	= new ContextMenu(this);
        oShareBrowser 	= new ShareBrowser(this);
        oTrayicon 		= new SysTrayIcon(this);
        oStatusUpdate	= new StatusUpdate(this);
        oMediaInfo		= new MediaInfo(this);
        oNowPlaying		= new NowPlaying(this);
        oGuiConfig		= new GuiConfig(this);

        nbDataContainer.CurrentPage = 0;
    }
コード例 #4
0
ファイル: ImageProcessor.cs プロジェクト: Remo/MediaData
 protected override void SetNewMetadata(MediaInfo newInfo, IWin32Window parentWindow)
 {
     string tempFilename = this.GetNewTempFilename();
     try
     {
         ShowProcessingOutput spo = ShowProcessingOutput.ShowProcessingOutput_GetForImages();
         Tool tool = this.PrepareTool(newInfo, tempFilename);
         Exception error = this.RunTool(newInfo, tool, spo, tempFilename, parentWindow);
         if (error != null)
         {
             throw error;
         }
     }
     catch
     {
         try
         {
             if (File.Exists(tempFilename))
             {
                 File.Delete(tempFilename);
             }
         }
         catch
         { }
         throw;
     }
 }
コード例 #5
0
ファイル: DeleteMedia.cs プロジェクト: gogosub77/Kanae
        public async Task<Boolean> Execute(MediaInfo mediaInfo)
        {
            // トランザクションとかないけど最悪でも画像が消えればいいのでアップロード情報を消すのは後にする
            await _mediaRepository.Delete(mediaInfo);
            await _uploadedInfoRepository.Delete(mediaInfo);

            return true;
        }
コード例 #6
0
        public Task<IMediaContent> Get(MediaInfo mediaInfo)
        {
            var filePath = GetPath(mediaInfo);
            if (!File.Exists(filePath))
                return null;

            return Task.FromResult<IMediaContent>(new FileSystemMediaContent(filePath));
        }
コード例 #7
0
 private static void IndexEntries(string videoFile, MediaInfo info, IndexDatabase database)
 {
     TimeSpan totalDuration = info.GetDuration();
     for (var startTime = TimeSpan.FromSeconds(0); startTime < totalDuration; startTime += PlaybackDuration)
     {
         IndexEntriesAtIndex(videoFile, startTime, info.GetFramerate(), totalDuration, database);
     }
 }
コード例 #8
0
ファイル: Processor.cs プロジェクト: Remo/MediaData
 protected Processor(string fullFilename)
 {
     if (!File.Exists(fullFilename))
     {
         throw new FileNotFoundException(fullFilename);
     }
     this.SetFullFilename(fullFilename);
     this._info = this.GetInfo(fullFilename);
 }
コード例 #9
0
        public Task Delete(MediaInfo mediaInfo)
        {
            var filePath = GetPath(mediaInfo);
            if (!File.Exists(filePath))
                return Utility.EmptyTask;

            File.Delete(filePath);

            return Utility.EmptyTask;
        }
コード例 #10
0
ファイル: MediaS3Repository.cs プロジェクト: gogosub77/Kanae
        public Task<IMediaContent> Get(MediaInfo mediaInfo)
        {
            var key = mediaInfo.UserId.ToSHA256Hash() + "/" + mediaInfo.MediaId.ToString();

            return Task.FromResult(
                IsRemoteContentMode
                    ? new S3RemoteMediaContent(_client, _bucketName, key, (_retentionTime == TimeSpan.MaxValue ? DateTime.UtcNow.AddHours(24) : mediaInfo.CreatedAt + _retentionTime)) as IMediaContent
                    : new S3MediaContent(_client, _bucketName, key) as IMediaContent
            );
        }
コード例 #11
0
ファイル: MediaS3Repository.cs プロジェクト: gogosub77/Kanae
 public Task Create(MediaInfo mediaInfo, byte[] data)
 {
     var putObject = new PutObjectRequest()
     {
         BucketName = _bucketName,
         Key = mediaInfo.UserId.ToSHA256Hash() + "/" + mediaInfo.MediaId.ToString(),
         ContentType = mediaInfo.ContentType,
         InputStream = new MemoryStream(data),
     };
     return _client.PutObjectAsync(putObject);
 }
コード例 #12
0
        public Task Create(MediaInfo mediaInfo, byte[] data)
        {
            var filePath = GetPath(mediaInfo);
            var dir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            File.WriteAllBytes(filePath, data);

            return Utility.EmptyTask;
        }
コード例 #13
0
        private async Task SetMimeType(HttpClient httpClient, MediaInfo mediaInfo)
        {
            if (!String.IsNullOrWhiteSpace(mediaInfo.Title) && !String.IsNullOrWhiteSpace(mediaInfo.Type))
            {
                return;
            }

            var mediaUri = new Uri(WebUtility.UrlDecode(mediaInfo.Uri).Trim());
            String mediaFilename;
            try { mediaFilename = UriUtility.GetFileName(mediaUri.AbsolutePath); }
            catch (Exception) { mediaFilename = null; }
            if (String.IsNullOrWhiteSpace(mediaInfo.Title))
            {
                mediaInfo.Title = mediaFilename;
            }

            if (String.IsNullOrWhiteSpace(mediaInfo.Type))
            {
                if (!String.IsNullOrWhiteSpace(mediaFilename))
                {
                    var extension = UriUtility.GetExtension(mediaFilename);
                    if (!String.IsNullOrWhiteSpace(extension))
                    {
                        extension = extension.Substring(1).ToLower();
                        var mimeType = MimeTypes.FirstOrDefault(mt => mt.Extensions.Any(ext => extension == ext));
                        if (mimeType != null)
                        {
                            mediaInfo.Type = mimeType.Type;
                            return;
                        }
                    }
                }

                var httpRequest = new HttpRequestMessage() { RequestUri = mediaUri, Method = HttpMethod.Head };
                try
                {
                    var contentType = (await httpClient.GetAsync(mediaUri).TimeoutAfter(5000)).Content.Headers.ContentType;
                    if (contentType != null)
                    {
                        mediaInfo.Type = contentType.MediaType;
                        return;
                    }
                }
                catch (Exception) { }

                mediaInfo.Type = "video/mp4";
            }
        }
コード例 #14
0
        public async Task Create(MediaInfo mediaInfo)
        {
            using (var ctx = new EfStorageDbContext())
            {
                var mediaInfoEntity = new EfStorageDbContext.MediaInfoEntity()
                {
                    UserId = mediaInfo.UserId,
                    MediaId = mediaInfo.MediaId,
                    CreatedAt = mediaInfo.CreatedAt,
                    ContentType = mediaInfo.ContentType,
                };
                ctx.MediaInfo.Add(mediaInfoEntity);

                await ctx.SaveChangesAsync();
            }
        }
コード例 #15
0
        public override async Task<MediaInfo[]> GetMediaInfosAsync(Uri Url) {
            if (!this.IsMatch(Url)) throw new NotSupportedException("不正確的網址");
            string EmbedUrl = $"http://www.dailymotion.com/embed/video/{GetMediaId(Url.OriginalString)}";//取得外連播放器連結
            JObject MediaJObject = await GetMediaJson(EmbedUrl);
            OnProcess?.Invoke(this, 0.2);

            var p = MediaJObject["metadata"]?["qualities"]?["240"]?[0].Value<JObject>();

            JObject Qualities = MediaJObject["metadata"]?["qualities"]?.Value<JObject>();

            MediaInfo Templet = new MediaInfo();//資料樣板
            Templet.ExtractorType = typeof(DailymotionExtractor);
            Templet.SourceUrl = Url;
            Templet.Name = MediaJObject["metadata"]?["title"].Value<string>();
            Templet.Attributes["author"] = MediaJObject["metadata"]?["owner"]?["username"].Value<string>();
            Templet.Duration = MediaJObject["metadata"]?["duration"].Value<int>() ?? 0;
            Templet.Thumbnail = new Uri(MediaJObject["metadata"]?["poster_url"].Value<string>());

            List<MediaInfo> result = new List<MediaInfo>();

            double Process = 0.2;

            foreach (var i in Qualities) {
                int temp = 0;
                if (!int.TryParse(i.Key, out temp)) { continue; }

                JObject VideoData = i.Value[0].Value<JObject>();
                MediaInfo t = Templet.Clone();
                t.Type = MediaTypes.Video;
                t.RealUrl = new Uri(VideoData?["url"].Value<string>());
                t.Attributes["quality"] = i.Key;
                t.Attributes["size"] = GetSize(VideoData?["url"].Value<string>());
                t.Attributes["mime"] = "video/mp4";

                result.Add(t);

                Process += 0.8 / Qualities.Count;
                OnProcess?.Invoke(this, Process);
            }

            MediaInfo[] output = result.ToArray();
            OnCompleted?.Invoke(this, output);
            return output;
        }
コード例 #16
0
ファイル: Media.cs プロジェクト: Mouaijin/DownloadSort
 ///<summary>Used to create a stream-specific object, such as an audio
 ///stream, for use by an existing MediaFile object.</summary>
 ///<param name="mediaInfo">A pre-initialized MediaInfo object.</param>
 ///<param name="kind">A defined value from StreamKind enum.</param>
 ///<param name="id">The MediaInfo ID for this stream.</param>
 public Media(MediaInfo mediaInfo, StreamKind kind, int id)
 {
     string errorText;
     this.mediaInfo = mediaInfo;
     if (mediaInfo == null) {
         errorText = "MediaInfo object cannot be null.";
         throw new ArgumentNullException(errorText);
     }
     if (!isMediaInfoDllCompatible()) {
         errorText = "Incompatible version of MediaInfo.DLL";
         throw new InvalidOperationException(errorText);
     }
     this.kind = kind;
     if (!Enum.IsDefined(typeof(StreamKind), (object)kind)) {
         errorText = "Invalid value for StreamKind";
         throw new ArgumentOutOfRangeException(errorText);
     }
     this.id = id;
 }
コード例 #17
0
    // Load Media Info
    public static MediaInfo GetMediaInfo(string mediaId)
    {
        DbCommand comm = DataAccessClass.CreateCommand();
          comm.CommandText = "StoreGetMediaDetails";
          DbParameter param = comm.CreateParameter();
          param.ParameterName = "@MediaID";
          param.Value = mediaId;
          param.DbType = DbType.Int32;
          comm.Parameters.Add(param);

          DataTable table = DataAccessClass.ExecuteSelectCommand(comm);
          MediaInfo info = new MediaInfo();
          if (table.Rows.Count > 0)
          {
        info.ShopMenuId = Int32.Parse(table.Rows[0]["ShopMenuID"].ToString());
        info.MediaName = table.Rows[0]["MediaName"].ToString();
        info.MediaDescription = table.Rows[0]["MediaDescription"].ToString();
          }
         return info;
    }
コード例 #18
0
        public async Task Create(MediaInfo mediaInfo)
        {
            var client = CreateTableClient();
            
            // テーブル取得するよ
            var table = client.GetTableReference("MediaInfo");

            // データ突っ込むよ
            try
            {
                // RowKeyが01_で始まるのは時刻で(降順)ソートされたデータ、02_で始まるのはGuid
                var tableResultTask = table.ExecuteAsync(TableOperation.InsertOrReplace(new MediaInfoEntity(mediaInfo)));
                var tableSortedResultTask = table.ExecuteAsync(TableOperation.InsertOrReplace(new MediaInfoSortedEntity(mediaInfo)));
                await Task.WhenAll(tableResultTask, tableSortedResultTask);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

        }
コード例 #19
0
        public static MediaInfo GetMediaInfo(InternalMediaInfoResult data)
        {
            var internalStreams = data.streams ?? new MediaStreamInfo[] { };

            var info = new MediaInfo
            {
                MediaStreams = internalStreams.Select(s => GetMediaStream(s, data.format))
                    .Where(i => i != null)
                    .ToList()
            };

            if (data.format != null)
            {
                info.Format = data.format.format_name;

                if (!string.IsNullOrEmpty(data.format.bit_rate))
                {
                    info.TotalBitrate = int.Parse(data.format.bit_rate, UsCulture);
                }
            }

            return info;
        }
コード例 #20
0
ファイル: FailedProcessor.cs プロジェクト: Remo/MediaData
 protected override void SetNewMetadata(MediaInfo newInfo, IWin32Window parentWindow)
 {
     throw new Exception(string.Format(i18n.Failed_process_file_X, this.FullFilename));
 }
コード例 #21
0
        private void Form1_Load(object sender, System.EventArgs e)
        {
            //Test if version of DLL is compatible : 3rd argument is "version of DLL tested;Your application name;Your application version"
            String    ToDisplay;
            MediaInfo MI = new MediaInfo();

            ToDisplay = MI.Option("Info_Version", "0.7.0.0;MediaInfoDLL_Example_CS;0.7.0.0");
            if (ToDisplay.Length == 0)
            {
                richTextBox1.Text = "MediaInfo.Dll: this version of the DLL is not compatible";
                return;
            }

            //Information about MediaInfo
            ToDisplay += "\r\n\r\nInfo_Parameters\r\n";
            ToDisplay += MI.Option("Info_Parameters");

            ToDisplay += "\r\n\r\nInfo_Capacities\r\n";
            ToDisplay += MI.Option("Info_Capacities");

            ToDisplay += "\r\n\r\nInfo_Codecs\r\n";
            ToDisplay += MI.Option("Info_Codecs");

            //An example of how to use the library
            ToDisplay += "\r\n\r\nOpen\r\n";
            MI.Open("Example.ogg");

            ToDisplay += "\r\n\r\nInform with Complete=false\r\n";
            MI.Option("Complete");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nInform with Complete=true\r\n";
            MI.Option("Complete", "1");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nCustom Inform\r\n";
            MI.Option("Inform", "General;File size is %FileSize% bytes");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n";
            ToDisplay += MI.Get(0, 0, "FileSize");

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n";
            ToDisplay += MI.Get(0, 0, 46);

            ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n";
            ToDisplay += MI.Count_Get(StreamKind.Audio);

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n";
            ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount");

            ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n";
            ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount");

            ToDisplay += "\r\n\r\nClose\r\n";
            MI.Close();

            //Example with a stream
            //ToDisplay+="\r\n"+ExampleWithStream()+"\r\n";

            //Displaying the text
            richTextBox1.Text = ToDisplay;
        }
コード例 #22
0
        public RawFile(NancyContext ctx, SVR_VideoLocal vl, int level, int uid)
        {
            if (vl != null)
            {
                id = vl.VideoLocalID;

                crc32    = vl.CRC32;
                ed2khash = vl.ED2KHash;
                md5      = vl.MD5;
                sha1     = vl.SHA1;

                created  = vl.DateTimeCreated;
                updated  = vl.DateTimeUpdated;
                duration = vl.Duration;

                if (vl.ReleaseGroup != null)
                {
                    group_full  = vl.ReleaseGroup.GroupName;
                    group_short = vl.ReleaseGroup.GroupNameShort;
                    group_id    = vl.ReleaseGroup.AniDB_ReleaseGroupID;
                }

                size        = vl.FileSize;
                hash        = vl.Hash;
                hash_source = vl.HashSource;

                is_ignored = vl.IsIgnored;
                VideoLocal_User vl_user = vl.GetUserRecord(uid);
                if (vl_user != null)
                {
                    offset = vl_user.ResumePosition;
                }
                else
                {
                    offset = 0;
                }

                VideoLocal_Place place = vl.GetBestVideoLocalPlace();
                if (place != null)
                {
                    filename            = place.FilePath;
                    videolocal_place_id = place.VideoLocal_Place_ID;
                    import_folder_id    = place.ImportFolderID;
                }

                if (vl.EpisodeCrossRefs.Count == 0)
                {
                    recognized = false;
                }
                else
                {
                    recognized = true;
                }

                if (vl.Media != null && (level > 1 || level == 0))
                {
                    media = new MediaInfo();

                    url = APIHelper.ConstructVideoLocalStream(ctx, uid, vl.Media.Id, "file." + vl.Media.Container, false);

                    MediaInfo new_media = new MediaInfo();

                    new_media.AddGeneral(MediaInfo.General.format, vl.Media.Container);
                    new_media.AddGeneral(MediaInfo.General.duration, vl.Media.Duration);
                    new_media.AddGeneral(MediaInfo.General.id, vl.Media.Id);
                    new_media.AddGeneral(MediaInfo.General.overallbitrate, vl.Media.Bitrate);

                    if (vl.Media.Parts != null)
                    {
                        new_media.AddGeneral(MediaInfo.General.size, vl.Media.Parts[0].Size);

                        foreach (Shoko.Models.PlexAndKodi.Stream p in vl.Media.Parts[0].Streams)
                        {
                            switch (p.StreamType)
                            {
                            //video
                            case "1":
                                new_media.AddVideo(p);
                                break;

                            //audio
                            case "2":
                                new_media.AddAudio(p);
                                break;

                            //subtitle
                            case "3":
                                new_media.AddSubtitle(p);
                                break;

                            //menu
                            case "4":
                                Dictionary <string, string> mdict = new Dictionary <string, string>();
                                //TODO APIv2: menu object could be usefull for external players
                                new_media.AddMenu(mdict);
                                break;
                            }
                        }
                    }

                    media = new_media;
                }
            }
        }
コード例 #23
0
        public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProbeDelay, bool isLiveStream, CancellationToken cancellationToken)
        {
            var originalRuntime = mediaSource.RunTimeTicks;

            var now = DateTime.UtcNow;

            MediaInfo mediaInfo     = null;
            var       cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N") + ".json");

            if (!string.IsNullOrEmpty(cacheKey))
            {
                try
                {
                    mediaInfo = _jsonSerializer.DeserializeFromFile <MediaInfo>(cacheFilePath);

                    //_logger.LogDebug("Found cached media info");
                }
                catch (Exception ex)
                {
                    _logger.LogDebug(ex, "_jsonSerializer.DeserializeFromFile threw an exception.");
                }
            }

            if (mediaInfo == null)
            {
                if (addProbeDelay)
                {
                    var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
                    delayMs = Math.Max(3000, delayMs);
                    await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
                }

                if (isLiveStream)
                {
                    mediaSource.AnalyzeDurationMs = 3000;
                }

                mediaInfo = await _mediaEncoder().GetMediaInfo(new MediaInfoRequest
                {
                    MediaSource     = mediaSource,
                    MediaType       = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
                    ExtractChapters = false
                }, cancellationToken).ConfigureAwait(false);

                if (cacheFilePath != null)
                {
                    _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(cacheFilePath));
                    _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath);

                    //_logger.LogDebug("Saved media info to {0}", cacheFilePath);
                }
            }

            var mediaStreams = mediaInfo.MediaStreams;

            if (isLiveStream && !string.IsNullOrEmpty(cacheKey))
            {
                var newList = new List <MediaStream>();
                newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1));
                newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1));

                foreach (var stream in newList)
                {
                    stream.Index    = -1;
                    stream.Language = null;
                }

                mediaStreams = newList;
            }

            _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));

            mediaSource.Bitrate       = mediaInfo.Bitrate;
            mediaSource.Container     = mediaInfo.Container;
            mediaSource.Formats       = mediaInfo.Formats;
            mediaSource.MediaStreams  = mediaStreams;
            mediaSource.RunTimeTicks  = mediaInfo.RunTimeTicks;
            mediaSource.Size          = mediaInfo.Size;
            mediaSource.Timestamp     = mediaInfo.Timestamp;
            mediaSource.Video3DFormat = mediaInfo.Video3DFormat;
            mediaSource.VideoType     = mediaInfo.VideoType;

            mediaSource.DefaultSubtitleStreamIndex = null;

            if (isLiveStream)
            {
                // Null this out so that it will be treated like a live stream
                if (!originalRuntime.HasValue)
                {
                    mediaSource.RunTimeTicks = null;
                }
            }

            var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);

            if (audioStream == null || audioStream.Index == -1)
            {
                mediaSource.DefaultAudioStreamIndex = null;
            }
            else
            {
                mediaSource.DefaultAudioStreamIndex = audioStream.Index;
            }

            var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);

            if (videoStream != null)
            {
                if (!videoStream.BitRate.HasValue)
                {
                    var width = videoStream.Width ?? 1920;

                    if (width >= 3000)
                    {
                        videoStream.BitRate = 30000000;
                    }

                    else if (width >= 1900)
                    {
                        videoStream.BitRate = 20000000;
                    }

                    else if (width >= 1200)
                    {
                        videoStream.BitRate = 8000000;
                    }

                    else if (width >= 700)
                    {
                        videoStream.BitRate = 2000000;
                    }
                }

                // This is coming up false and preventing stream copy
                videoStream.IsAVC = null;
            }

            if (isLiveStream)
            {
                mediaSource.AnalyzeDurationMs = 3000;
            }

            // Try to estimate this
            mediaSource.InferTotalBitrate(true);
        }
コード例 #24
0
 ///<summary>MultiStreamCommon constructor.</summary>
 ///<param name="mediaInfo">A MediaInfo object.</param>
 ///<param name="kind">A MediaInfo StreamKind.</param>
 ///<param name="id">The MediaInfo ID for this audio stream.</param>
 public BaseStreamCommons(MediaInfo mediaInfo, StreamKind kind, int id)
     : base(mediaInfo, kind, id)
 {
 }
コード例 #25
0
ファイル: Convert.cs プロジェクト: maz0r/jmmserver
        private static Stream TranslateAudioStream(MediaInfo m, int num)
        {
            Stream s = new Stream();
            s.Id = m.Get(StreamKind.Audio, num, "UniqueID");
            s.CodecID = (m.Get(StreamKind.Audio, num, "CodecID"));
            s.Codec = TranslateCodec(m.Get(StreamKind.Audio, num, "Codec"));
            string title = m.Get(StreamKind.Audio, num, "Title");
            if (!string.IsNullOrEmpty(title))
                s.Title = title;
            s.StreamType = "2";
            string lang = m.Get(StreamKind.Audio, num, "Language/String3");
            if (!string.IsNullOrEmpty(lang))
                s.LanguageCode = PostTranslateCode3(lang); ;
            string lan = PostTranslateLan(GetLanguageFromCode3(lang, m.Get(StreamKind.Audio, num, "Language/String1")));
            if (!string.IsNullOrEmpty(lan))
                s.Language = lan;
            string duration = m.Get(StreamKind.Audio, num, "Duration");
            if (!string.IsNullOrEmpty(duration))
                s.Duration = duration;
            int brate = BiggerFromList(m.Get(StreamKind.Audio, num, "BitRate"));
            if (brate != 0)
                s.Bitrate = Math.Round(brate / 1000F).ToString(CultureInfo.InvariantCulture);
            int bitdepth = m.GetInt(StreamKind.Audio, num, "BitDepth");
            if (bitdepth != 0)
                s.BitDepth = bitdepth.ToString(CultureInfo.InvariantCulture);
            string fprofile = m.Get(StreamKind.Audio, num, "Format_Profile");
            if (!string.IsNullOrEmpty(fprofile))
            {
                if ((fprofile.ToLower() != "layer 3") && (fprofile.ToLower() != "dolby digital") && (fprofile.ToLower() != "pro") && (fprofile.ToLower() != "layer 2"))
                    s.Profile = fprofile.ToLower(CultureInfo.InvariantCulture);
                if (fprofile.ToLower().StartsWith("ma"))
                    s.Profile = "ma";
            }
            string fset = m.Get(StreamKind.Audio, num, "Format_Settings");
            if ((!string.IsNullOrEmpty(fset)) && (fset == "Little / Signed") && (s.Codec == "pcm") && (bitdepth==16))
            {
                s.Profile = "pcm_s16le";
            }
            else if ((!string.IsNullOrEmpty(fset)) && (fset == "Big / Signed") && (s.Codec == "pcm") && (bitdepth == 16))
            {
                 s.Profile = "pcm_s16be";
            }
            else if ((!string.IsNullOrEmpty(fset)) && (fset == "Little / Unsigned") && (s.Codec == "pcm") &&
                     (bitdepth == 8))
            {
                s.Profile = "pcm_u8";
            }
            string id = m.Get(StreamKind.Audio, num, "ID");
            if (!string.IsNullOrEmpty(id))
            {
                int idx;
                if (int.TryParse(id, out idx))
                {
                    s.Index = idx.ToString(CultureInfo.InvariantCulture);
                }
            }
            int pa = BiggerFromList(m.Get(StreamKind.Audio, num, "SamplingRate"));
            if (pa!=0)
                s.SamplingRate=pa.ToString(CultureInfo.InvariantCulture);
            int channels = BiggerFromList(m.Get(StreamKind.Audio, num, "Channel(s)"));
            if (channels != 0)
                s.Channels=channels.ToString(CultureInfo.InvariantCulture);
            int channelso = BiggerFromList(m.Get(StreamKind.Audio, num, "Channel(s)_Original"));
            if ((channelso!=0))
                s.Channels = channelso.ToString(CultureInfo.InvariantCulture);
            
            string bitRateMode = m.Get(StreamKind.Audio, num, "BitRate_Mode");
            if (!string.IsNullOrEmpty(bitRateMode))
                s.BitrateMode = bitRateMode.ToLower(CultureInfo.InvariantCulture);
            string dialnorm = m.Get(StreamKind.Audio, num, "dialnorm");
            if (!string.IsNullOrEmpty(dialnorm))
                s.DialogNorm=dialnorm;
            dialnorm = m.Get(StreamKind.Audio, num, "dialnorm_Average");
            if (!string.IsNullOrEmpty(dialnorm))
                s.DialogNorm = dialnorm;

            string def = m.Get(StreamKind.Text, num, "Default");
            if (!string.IsNullOrEmpty(def))
            {
                if (def.ToLower(CultureInfo.InvariantCulture) == "yes")
                    s.Default = "1";
            }
            string forced = m.Get(StreamKind.Text, num, "Forced");
            if (!string.IsNullOrEmpty(forced))
            {
                if (forced.ToLower(CultureInfo.InvariantCulture) == "yes")
                    s.Forced = "1";
            }
            return s;
        }
コード例 #26
0
        private void SetAudioInfoFromTags(MediaInfo audio, Dictionary <string, string> tags)
        {
            var composer = FFProbeHelpers.GetDictionaryValue(tags, "composer");

            if (!string.IsNullOrWhiteSpace(composer))
            {
                foreach (var person in Split(composer, false))
                {
                    audio.People.Add(new BaseItemPerson {
                        Name = person, Type = PersonType.Composer
                    });
                }
            }

            var conductor = FFProbeHelpers.GetDictionaryValue(tags, "conductor");

            if (!string.IsNullOrWhiteSpace(conductor))
            {
                foreach (var person in Split(conductor, false))
                {
                    audio.People.Add(new BaseItemPerson {
                        Name = person, Type = PersonType.Conductor
                    });
                }
            }

            var lyricist = FFProbeHelpers.GetDictionaryValue(tags, "lyricist");

            if (!string.IsNullOrWhiteSpace(lyricist))
            {
                foreach (var person in Split(lyricist, false))
                {
                    audio.People.Add(new BaseItemPerson {
                        Name = person, Type = PersonType.Lyricist
                    });
                }
            }
            // Check for writer some music is tagged that way as alternative to composer/lyricist
            var writer = FFProbeHelpers.GetDictionaryValue(tags, "writer");

            if (!string.IsNullOrWhiteSpace(writer))
            {
                foreach (var person in Split(writer, false))
                {
                    audio.People.Add(new BaseItemPerson {
                        Name = person, Type = PersonType.Writer
                    });
                }
            }

            audio.Album = FFProbeHelpers.GetDictionaryValue(tags, "album");

            var artists = FFProbeHelpers.GetDictionaryValue(tags, "artists");

            if (!string.IsNullOrWhiteSpace(artists))
            {
                audio.Artists = SplitArtists(artists, new[] { '/', ';' }, false)
                                .DistinctNames()
                                .ToList();
            }
            else
            {
                var artist = FFProbeHelpers.GetDictionaryValue(tags, "artist");
                if (string.IsNullOrWhiteSpace(artist))
                {
                    audio.Artists.Clear();
                }
                else
                {
                    audio.Artists = SplitArtists(artist, _nameDelimiters, true)
                                    .DistinctNames()
                                    .ToList();
                }
            }

            var albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "albumartist");

            if (string.IsNullOrWhiteSpace(albumArtist))
            {
                albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album artist");
            }
            if (string.IsNullOrWhiteSpace(albumArtist))
            {
                albumArtist = FFProbeHelpers.GetDictionaryValue(tags, "album_artist");
            }

            if (string.IsNullOrWhiteSpace(albumArtist))
            {
                audio.AlbumArtists = new List <string>();
            }
            else
            {
                audio.AlbumArtists = SplitArtists(albumArtist, _nameDelimiters, true)
                                     .DistinctNames()
                                     .ToList();
            }

            if (audio.AlbumArtists.Count == 0)
            {
                audio.AlbumArtists = audio.Artists.Take(1).ToList();
            }

            // Track number
            audio.IndexNumber = GetDictionaryDiscValue(tags, "track");

            // Disc number
            audio.ParentIndexNumber = GetDictionaryDiscValue(tags, "disc");

            // If we don't have a ProductionYear try and get it from PremiereDate
            if (audio.PremiereDate.HasValue && !audio.ProductionYear.HasValue)
            {
                audio.ProductionYear = audio.PremiereDate.Value.ToLocalTime().Year;
            }

            // There's several values in tags may or may not be present
            FetchStudios(audio, tags, "organization");
            FetchStudios(audio, tags, "ensemble");
            FetchStudios(audio, tags, "publisher");
            FetchStudios(audio, tags, "label");

            // These support mulitple values, but for now we only store the first.
            var mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Artist Id"));

            if (mb == null)
            {
                mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMARTISTID"));
            }
            audio.SetProviderId(MetadataProviders.MusicBrainzAlbumArtist, mb);

            mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Artist Id"));
            if (mb == null)
            {
                mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ARTISTID"));
            }
            audio.SetProviderId(MetadataProviders.MusicBrainzArtist, mb);

            mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Album Id"));
            if (mb == null)
            {
                mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_ALBUMID"));
            }
            audio.SetProviderId(MetadataProviders.MusicBrainzAlbum, mb);

            mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Group Id"));
            if (mb == null)
            {
                mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASEGROUPID"));
            }
            audio.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, mb);

            mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MusicBrainz Release Track Id"));
            if (mb == null)
            {
                mb = GetMultipleMusicBrainzId(FFProbeHelpers.GetDictionaryValue(tags, "MUSICBRAINZ_RELEASETRACKID"));
            }
            audio.SetProviderId(MetadataProviders.MusicBrainzTrack, mb);
        }
コード例 #27
0
        public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType videoType, bool isAudio, string path, MediaProtocol protocol)
        {
            var info = new MediaInfo
            {
                Path     = path,
                Protocol = protocol
            };

            FFProbeHelpers.NormalizeFFProbeResult(data);
            SetSize(data, info);

            var internalStreams = data.streams ?? new MediaStreamInfo[] { };

            info.MediaStreams = internalStreams.Select(s => GetMediaStream(isAudio, s, data.format))
                                .Where(i => i != null)
                                .ToList();

            if (data.format != null)
            {
                info.Container = data.format.format_name;

                if (!string.IsNullOrEmpty(data.format.bit_rate))
                {
                    int value;
                    if (int.TryParse(data.format.bit_rate, NumberStyles.Any, _usCulture, out value))
                    {
                        info.Bitrate = value;
                    }
                }
            }

            var tags          = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            var tagStreamType = isAudio ? "audio" : "video";

            if (data.streams != null)
            {
                var tagStream = data.streams.FirstOrDefault(i => string.Equals(i.codec_type, tagStreamType, StringComparison.OrdinalIgnoreCase));

                if (tagStream != null && tagStream.tags != null)
                {
                    foreach (var pair in tagStream.tags)
                    {
                        tags[pair.Key] = pair.Value;
                    }
                }
            }

            if (data.format != null && data.format.tags != null)
            {
                foreach (var pair in data.format.tags)
                {
                    tags[pair.Key] = pair.Value;
                }
            }

            FetchGenres(info, tags);
            var shortOverview = FFProbeHelpers.GetDictionaryValue(tags, "description");
            var overview      = FFProbeHelpers.GetDictionaryValue(tags, "synopsis");

            if (string.IsNullOrWhiteSpace(overview))
            {
                overview      = shortOverview;
                shortOverview = null;
            }
            if (string.IsNullOrWhiteSpace(overview))
            {
                overview = FFProbeHelpers.GetDictionaryValue(tags, "desc");
            }

            if (!string.IsNullOrWhiteSpace(overview))
            {
                info.Overview = overview;
            }

            if (!string.IsNullOrWhiteSpace(shortOverview))
            {
                info.ShortOverview = shortOverview;
            }

            var title = FFProbeHelpers.GetDictionaryValue(tags, "title");

            if (!string.IsNullOrWhiteSpace(title))
            {
                info.Name = title;
            }

            info.ProductionYear = FFProbeHelpers.GetDictionaryNumericValue(tags, "date");

            // Several different forms of retaildate
            info.PremiereDate = FFProbeHelpers.GetDictionaryDateTime(tags, "retaildate") ??
                                FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ??
                                FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ??
                                FFProbeHelpers.GetDictionaryDateTime(tags, "date");

            if (isAudio)
            {
                SetAudioRuntimeTicks(data, info);

                // tags are normally located under data.format, but we've seen some cases with ogg where they're part of the info stream
                // so let's create a combined list of both

                SetAudioInfoFromTags(info, tags);
            }
            else
            {
                FetchStudios(info, tags, "copyright");

                var iTunEXTC = FFProbeHelpers.GetDictionaryValue(tags, "iTunEXTC");
                if (!string.IsNullOrWhiteSpace(iTunEXTC))
                {
                    var parts = iTunEXTC.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    // Example
                    // mpaa|G|100|For crude humor
                    if (parts.Length > 1)
                    {
                        info.OfficialRating = parts[1];

                        if (parts.Length > 3)
                        {
                            info.OfficialRatingDescription = parts[3];
                        }
                    }
                }

                var itunesXml = FFProbeHelpers.GetDictionaryValue(tags, "iTunMOVI");
                if (!string.IsNullOrWhiteSpace(itunesXml))
                {
                    FetchFromItunesInfo(itunesXml, info);
                }

                if (data.format != null && !string.IsNullOrEmpty(data.format.duration))
                {
                    info.RunTimeTicks = TimeSpan.FromSeconds(double.Parse(data.format.duration, _usCulture)).Ticks;
                }

                FetchWtvInfo(info, data);

                if (data.Chapters != null)
                {
                    info.Chapters = data.Chapters.Select(GetChapterInfo).ToList();
                }

                ExtractTimestamp(info);

                var stereoMode = GetDictionaryValue(tags, "stereo_mode");
                if (string.Equals(stereoMode, "left_right", StringComparison.OrdinalIgnoreCase))
                {
                    info.Video3DFormat = Video3DFormat.FullSideBySide;
                }
            }

            return(info);
        }
コード例 #28
0
        private const int MaxSubtitleDescriptionExtractionLength = 100; // When extracting subtitles, the maximum length to consider (to avoid invalid filenames)

        private void FetchWtvInfo(MediaInfo video, InternalMediaInfoResult data)
        {
            if (data.format == null || data.format.tags == null)
            {
                return;
            }

            var genres = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/Genre");

            if (!string.IsNullOrWhiteSpace(genres))
            {
                var genreList = genres.Split(new[] { ';', '/', ',' }, StringSplitOptions.RemoveEmptyEntries)
                                .Where(i => !string.IsNullOrWhiteSpace(i))
                                .Select(i => i.Trim())
                                .ToList();

                // If this is empty then don't overwrite genres that might have been fetched earlier
                if (genreList.Count > 0)
                {
                    video.Genres = genreList;
                }
            }

            var officialRating = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/ParentalRating");

            if (!string.IsNullOrWhiteSpace(officialRating))
            {
                video.OfficialRating = officialRating;
            }

            var people = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaCredits");

            if (!string.IsNullOrEmpty(people))
            {
                video.People = people.Split(new[] { ';', '/' }, StringSplitOptions.RemoveEmptyEntries)
                               .Where(i => !string.IsNullOrWhiteSpace(i))
                               .Select(i => new BaseItemPerson {
                    Name = i.Trim(), Type = PersonType.Actor
                })
                               .ToList();
            }

            var year = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/OriginalReleaseTime");

            if (!string.IsNullOrWhiteSpace(year))
            {
                int val;

                if (int.TryParse(year, NumberStyles.Integer, _usCulture, out val))
                {
                    video.ProductionYear = val;
                }
            }

            var premiereDateString = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/MediaOriginalBroadcastDateTime");

            if (!string.IsNullOrWhiteSpace(premiereDateString))
            {
                DateTime val;

                // Credit to MCEBuddy: https://mcebuddy2x.codeplex.com/
                // DateTime is reported along with timezone info (typically Z i.e. UTC hence assume None)
                if (DateTime.TryParse(year, null, DateTimeStyles.None, out val))
                {
                    video.PremiereDate = val.ToUniversalTime();
                }
            }

            var description = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitleDescription");

            var subTitle = FFProbeHelpers.GetDictionaryValue(data.format.tags, "WM/SubTitle");

            // For below code, credit to MCEBuddy: https://mcebuddy2x.codeplex.com/

            // Sometimes for TV Shows the Subtitle field is empty and the subtitle description contains the subtitle, extract if possible. See ticket https://mcebuddy2x.codeplex.com/workitem/1910
            // The format is -> EPISODE/TOTAL_EPISODES_IN_SEASON. SUBTITLE: DESCRIPTION
            // OR -> COMMENT. SUBTITLE: DESCRIPTION
            // e.g. -> 4/13. The Doctor's Wife: Science fiction drama. When he follows a Time Lord distress signal, the Doctor puts Amy, Rory and his beloved TARDIS in grave danger. Also in HD. [AD,S]
            // e.g. -> CBeebies Bedtime Hour. The Mystery: Animated adventures of two friends who live on an island in the middle of the big city. Some of Abney and Teal's favourite objects are missing. [S]
            if (String.IsNullOrWhiteSpace(subTitle) && !String.IsNullOrWhiteSpace(description) && description.Substring(0, Math.Min(description.Length, MaxSubtitleDescriptionExtractionLength)).Contains(":")) // Check within the Subtitle size limit, otherwise from description it can get too long creating an invalid filename
            {
                string[] parts = description.Split(':');
                if (parts.Length > 0)
                {
                    string subtitle = parts[0];
                    try
                    {
                        if (subtitle.Contains("/")) // It contains a episode number and season number
                        {
                            string[] numbers = subtitle.Split(' ');
                            video.IndexNumber = int.Parse(numbers[0].Replace(".", "").Split('/')[0]);
                            int totalEpisodesInSeason = int.Parse(numbers[0].Replace(".", "").Split('/')[1]);

                            description = String.Join(" ", numbers, 1, numbers.Length - 1).Trim(); // Skip the first, concatenate the rest, clean up spaces and save it
                        }
                        else
                        {
                            throw new Exception(); // Switch to default parsing
                        }
                    }
                    catch                                                                                                  // Default parsing
                    {
                        if (subtitle.Contains("."))                                                                        // skip the comment, keep the subtitle
                        {
                            description = String.Join(".", subtitle.Split('.'), 1, subtitle.Split('.').Length - 1).Trim(); // skip the first
                        }
                        else
                        {
                            description = subtitle.Trim(); // Clean up whitespaces and save it
                        }
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(description))
            {
                video.Overview = description;
            }
        }
コード例 #29
0
        public void GetMediaInfo_Mp4MetaData_Success()
        {
            var bytes = File.ReadAllBytes("Test Data/Probing/video_mp4_metadata.json");
            var internalMediaInfoResult = JsonSerializer.Deserialize <InternalMediaInfoResult>(bytes, _jsonOptions);

            // subtitle handling requires a localization object, set a mock to return the input string
            var mockLocalization = new Mock <ILocalizationManager>();

            mockLocalization.Setup(x => x.GetLocalizedString(It.IsAny <string>())).Returns <string>(x => x);
            ProbeResultNormalizer localizedProbeResultNormalizer = new ProbeResultNormalizer(new NullLogger <EncoderValidatorTests>(), mockLocalization.Object);

            MediaInfo res = localizedProbeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_mp4_metadata.mkv", MediaProtocol.File);

            // [Video, Audio (Main), Audio (Commentary), Subtitle (Main, Spanish), Subtitle (Main, English), Subtitle (Commentary)
            Assert.Equal(6, res.MediaStreams.Count);

            Assert.NotNull(res.VideoStream);
            Assert.Equal(res.MediaStreams[0], res.VideoStream);
            Assert.Equal(0, res.VideoStream.Index);
            Assert.Equal("h264", res.VideoStream.Codec);
            Assert.Equal("High", res.VideoStream.Profile);
            Assert.Equal(MediaStreamType.Video, res.VideoStream.Type);
            Assert.Equal(358, res.VideoStream.Height);
            Assert.Equal(720, res.VideoStream.Width);
            Assert.Equal("2.40:1", res.VideoStream.AspectRatio);
            Assert.Equal("yuv420p", res.VideoStream.PixelFormat);
            Assert.Equal(31d, res.VideoStream.Level);
            Assert.Equal(1, res.VideoStream.RefFrames);
            Assert.True(res.VideoStream.IsAVC);
            Assert.Equal(120f, res.VideoStream.RealFrameRate);
            Assert.Equal("1/90000", res.VideoStream.TimeBase);
            Assert.Equal(1147365, res.VideoStream.BitRate);
            Assert.Equal(8, res.VideoStream.BitDepth);
            Assert.True(res.VideoStream.IsDefault);
            Assert.Equal("und", res.VideoStream.Language);

            Assert.Equal(MediaStreamType.Audio, res.MediaStreams[1].Type);
            Assert.Equal("aac", res.MediaStreams[1].Codec);
            Assert.Equal(7, res.MediaStreams[1].Channels);
            Assert.True(res.MediaStreams[1].IsDefault);
            Assert.Equal("eng", res.MediaStreams[1].Language);
            Assert.Equal("Surround 6.1", res.MediaStreams[1].Title);

            Assert.Equal(MediaStreamType.Audio, res.MediaStreams[2].Type);
            Assert.Equal("aac", res.MediaStreams[2].Codec);
            Assert.Equal(2, res.MediaStreams[2].Channels);
            Assert.False(res.MediaStreams[2].IsDefault);
            Assert.Equal("eng", res.MediaStreams[2].Language);
            Assert.Equal("Commentary", res.MediaStreams[2].Title);

            Assert.Equal("spa", res.MediaStreams[3].Language);
            Assert.Equal(MediaStreamType.Subtitle, res.MediaStreams[3].Type);
            Assert.Equal("DVDSUB", res.MediaStreams[3].Codec);
            Assert.Null(res.MediaStreams[3].Title);

            Assert.Equal("eng", res.MediaStreams[4].Language);
            Assert.Equal(MediaStreamType.Subtitle, res.MediaStreams[4].Type);
            Assert.Equal("mov_text", res.MediaStreams[4].Codec);
            Assert.Null(res.MediaStreams[4].Title);

            Assert.Equal("eng", res.MediaStreams[5].Language);
            Assert.Equal(MediaStreamType.Subtitle, res.MediaStreams[5].Type);
            Assert.Equal("mov_text", res.MediaStreams[5].Codec);
            Assert.Equal("Commentary", res.MediaStreams[5].Title);
        }
コード例 #30
0
        public static void ShowInfo()
        {
            try
            {
                string performer, title, album, genre, date, duration, text = "";
                long   fileSize = 0;
                string path     = core.get_property_string("path");

                if (path.Contains("://"))
                {
                    path = core.get_property_string("media-title");
                }

                int width  = core.get_property_int("video-params/w");
                int height = core.get_property_int("video-params/h");

                if (File.Exists(path))
                {
                    fileSize = new FileInfo(path).Length;

                    if (App.AudioTypes.Contains(path.Ext()))
                    {
                        using (MediaInfo mediaInfo = new MediaInfo(path))
                        {
                            performer = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Performer");
                            title     = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Title");
                            album     = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Album");
                            genre     = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Genre");
                            date      = mediaInfo.GetInfo(MediaInfoStreamKind.General, "Recorded_Date");
                            duration  = mediaInfo.GetInfo(MediaInfoStreamKind.Audio, "Duration/String");

                            if (performer != "")
                            {
                                text += "Artist: " + performer + "\n";
                            }
                            if (title != "")
                            {
                                text += "Title: " + title + "\n";
                            }
                            if (album != "")
                            {
                                text += "Album: " + album + "\n";
                            }
                            if (genre != "")
                            {
                                text += "Genre: " + genre + "\n";
                            }
                            if (date != "")
                            {
                                text += "Year: " + date + "\n";
                            }
                            if (duration != "")
                            {
                                text += "Length: " + duration + "\n";
                            }
                            text += "Size: " + mediaInfo.GetInfo(MediaInfoStreamKind.General, "FileSize/String") + "\n";
                            text += "Type: " + path.Ext().ToUpper();

                            core.commandv("show-text", text, "5000");
                            return;
                        }
                    }
                    else if (App.ImageTypes.Contains(path.Ext()))
                    {
                        using (MediaInfo mediaInfo = new MediaInfo(path))
                        {
                            text =
                                "Width: " + mediaInfo.GetInfo(MediaInfoStreamKind.Image, "Width") + "\n" +
                                "Height: " + mediaInfo.GetInfo(MediaInfoStreamKind.Image, "Height") + "\n" +
                                "Size: " + mediaInfo.GetInfo(MediaInfoStreamKind.General, "FileSize/String") + "\n" +
                                "Type: " + path.Ext().ToUpper();

                            core.commandv("show-text", text, "5000");
                            return;
                        }
                    }
                }

                TimeSpan position    = TimeSpan.FromSeconds(core.get_property_number("time-pos"));
                TimeSpan duration2   = TimeSpan.FromSeconds(core.get_property_number("duration"));
                string   videoFormat = core.get_property_string("video-format").ToUpper();
                string   audioCodec  = core.get_property_string("audio-codec-name").ToUpper();

                text = path.FileName() + "\n" +
                       FormatTime(position.TotalMinutes) + ":" +
                       FormatTime(position.Seconds) + " / " +
                       FormatTime(duration2.TotalMinutes) + ":" +
                       FormatTime(duration2.Seconds) + "\n" +
                       $"{width} x {height}\n";

                if (fileSize > 0)
                {
                    text += Convert.ToInt32(fileSize / 1024.0 / 1024.0) + " MB\n";
                }

                text += $"{videoFormat}\n{audioCodec}";

                core.commandv("show-text", text, "5000");
                string FormatTime(double value) => ((int)value).ToString("00");
            }
            catch (Exception e)
            {
                App.ShowException(e);
            }
        }
コード例 #31
0
        static void Main(string[] Args)
        {
            String    ToDisplay;
            MediaInfo MI = new MediaInfo();

            ToDisplay = MI.Option("Info_Version", "0.7.0.0;MediaInfoDLL_Example_CS;0.7.0.0");
            if (ToDisplay.Length == 0)
            {
                Console.Out.WriteLine("MediaInfo.Dll: this version of the DLL is not compatible");
                return;
            }

            //Information about MediaInfo
            ToDisplay += "\r\n\r\nInfo_Parameters\r\n";
            ToDisplay += MI.Option("Info_Parameters");

            ToDisplay += "\r\n\r\nInfo_Capacities\r\n";
            ToDisplay += MI.Option("Info_Capacities");

            ToDisplay += "\r\n\r\nInfo_Codecs\r\n";
            ToDisplay += MI.Option("Info_Codecs");

            //An example of how to use the library
            ToDisplay += "\r\n\r\nOpen\r\n";
            String File_Name;

            if (Args.Length == 0)
            {
                File_Name = "Example.ogg";
            }
            else
            {
                File_Name = Args[0];
            }
            MI.Open(File_Name);

            ToDisplay += "\r\n\r\nInform with Complete=false\r\n";
            MI.Option("Complete");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nInform with Complete=true\r\n";
            MI.Option("Complete", "1");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nCustom Inform\r\n";
            MI.Option("Inform", "General;File size is %FileSize% bytes");
            ToDisplay += MI.Inform();

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='FileSize'\r\n";
            ToDisplay += MI.Get(0, 0, "FileSize");

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter=46\r\n";
            ToDisplay += MI.Get(0, 0, 46);

            ToDisplay += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n";
            ToDisplay += MI.Count_Get(StreamKind.Audio);

            ToDisplay += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n";
            ToDisplay += MI.Get(StreamKind.General, 0, "AudioCount");

            ToDisplay += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n";
            ToDisplay += MI.Get(StreamKind.Audio, 0, "StreamCount");

            ToDisplay += "\r\n\r\nClose\r\n";
            MI.Close();

            //Displaying the text
            Console.Out.WriteLine(ToDisplay);
        }
コード例 #32
0
 public ChapterStreamBuilder(MediaInfo info, int number, int position)
     : base(info, number, position)
 {
 }
コード例 #33
0
 private String GetPath(MediaInfo mediaInfo)
 {
     return Path.Combine(_dataDirectory, Uri.EscapeDataString(mediaInfo.UserId), mediaInfo.MediaId + (GetExtensionFromContentType(mediaInfo.ContentType)));
 }
コード例 #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LanguageMediaStreamBuilder{TStream}"/> class.
 /// </summary>
 /// <param name="info">The media info object.</param>
 /// <param name="number">The stream number.</param>
 /// <param name="position">The stream position.</param>
 protected LanguageMediaStreamBuilder(MediaInfo info, int number, int position)
     : base(info, number, position)
 {
 }
コード例 #35
0
ファイル: Convert.cs プロジェクト: maz0r/jmmserver
        public static Media Convert(string filename)
        {
            int ex = 0;
            MediaInfo mi = new MediaInfo();
            if (mi == null)
                return null;
            try
            {
                if (!File.Exists(filename))
                    return null;
            }
            catch (Exception)
            {
                return null;
            }
            try
            {
                mi.Open(filename);
                ex = 1;
                Media m = new Media();
                Part p = new Part();
                Stream VideoStream = null;
                int video_count = mi.GetInt(StreamKind.General, 0, "VideoCount");
                int audio_count = mi.GetInt(StreamKind.General, 0, "AudioCount");
                int text_count = mi.GetInt(StreamKind.General, 0, "TextCount");
                m.Duration = p.Duration = mi.Get(StreamKind.General, 0, "Duration");
                m.Container = p.Container = TranslateContainer(mi.Get(StreamKind.General, 0, "Format"));
                string codid = mi.Get(StreamKind.General, 0, "CodecID");
                if ((!string.IsNullOrEmpty(codid)) && (codid.Trim().ToLower() == "qt"))
                    m.Container = p.Container= "mov";

                int brate = mi.GetInt(StreamKind.General, 0, "BitRate");
                if (brate != 0)
                    m.Bitrate = Math.Round(brate / 1000F).ToString(CultureInfo.InvariantCulture);
                p.Size = mi.Get(StreamKind.General, 0, "FileSize");
                //m.Id = p.Id = mi.Get(StreamKind.General, 0, "UniqueID");

                ex = 2;
                List<Stream> streams = new List<Stream>();
                int iidx = 0;
                if (video_count > 0)
                {
                    for (int x = 0; x < video_count; x++)
                    {
                        Stream s = TranslateVideoStream(mi, x);
                        if (x == 0)
                        {
                            VideoStream = s;
                            m.Width = s.Width;
                            m.Height = s.Height;
                            if (!string.IsNullOrEmpty(m.Height))
                            {
                                
                                if (!string.IsNullOrEmpty(m.Width))
                                {
                                    m.VideoResolution = GetResolution(int.Parse(m.Width),int.Parse(m.Height));
                                    m.AspectRatio = GetAspectRatio(float.Parse(m.Width), float.Parse(m.Height), s.PA);

                                }
                            }
                            if (!string.IsNullOrEmpty(s.FrameRate))
                            {
                                float fr = System.Convert.ToSingle(s.FrameRate);
                                m.VideoFrameRate = ((int)Math.Round(fr)).ToString(CultureInfo.InvariantCulture);
                                if (!string.IsNullOrEmpty(s.ScanType))
                                {
                                    if (s.ScanType.ToLower().Contains("int"))
                                        m.VideoFrameRate += "i";
                                    else
                                        m.VideoFrameRate += "p";
                                }
                                else
                                    m.VideoFrameRate += "p";
                                if ((m.VideoFrameRate == "25p") || (m.VideoFrameRate == "25i"))
                                    m.VideoFrameRate = "PAL";
                                else if ((m.VideoFrameRate == "30p") || (m.VideoFrameRate == "30i"))
                                    m.VideoFrameRate = "NTSC";
                            }
                            m.VideoCodec = s.Codec;
                            if (!string.IsNullOrEmpty(m.Duration) && !string.IsNullOrEmpty(s.Duration))
                            {
                                if (int.Parse(s.Duration) > int.Parse(m.Duration))
                                    m.Duration = p.Duration = s.Duration;
                            }
                            if (video_count == 1)
                            {
                                s.Default = null;
                                s.Forced = null;
                            }
                        }

                        if (m.Container != "mkv")
                        {
                            s.Index = iidx.ToString(CultureInfo.InvariantCulture);
                            iidx++;
                        }
                        streams.Add(s);
                    }
                }
                ex = 3;
                int totalsoundrate = 0;
                if (audio_count > 0)
                {
                    for (int x = 0; x < audio_count; x++)
                    {
                        Stream s = TranslateAudioStream(mi, x);
                        if ((s.Codec == "adpcm") && (p.Container == "flv"))
                            s.Codec = "adpcm_swf";
                        if (x == 0)
                        {
                            m.AudioCodec = s.Codec;
                            m.AudioChannels = s.Channels;
                            if (!string.IsNullOrEmpty(m.Duration) && !string.IsNullOrEmpty(s.Duration))
                            {
                                if (int.Parse(s.Duration) > int.Parse(m.Duration))
                                    m.Duration = p.Duration = s.Duration;
                            }
                            if (audio_count == 1)
                            {
                                s.Default = null;
                                s.Forced = null;
                            }
                        }
                        if (!string.IsNullOrEmpty(s.Bitrate))
                        {
                            totalsoundrate += int.Parse(s.Bitrate);
                        }
                            if (m.Container != "mkv")
                        {
                            s.Index = iidx.ToString(CultureInfo.InvariantCulture);
                            iidx++;
                        }
                        streams.Add(s);
                    }
                }
                if ((VideoStream!=null) && (string.IsNullOrEmpty(VideoStream.Bitrate) && (!string.IsNullOrEmpty(m.Bitrate))))
                {
                    VideoStream.Bitrate = (int.Parse(m.Bitrate) - totalsoundrate).ToString(CultureInfo.InvariantCulture);
                }


                ex = 4;
                if (text_count > 0)
                {
                    for (int x = 0; x < audio_count; x++)
                    {
                        Stream s = TranslateTextStream(mi, x);
                        streams.Add(s);
                        if (text_count == 1)
                        {
                            s.Default = null;
                            s.Forced = null;
                        }
                        if (m.Container != "mkv")
                        {
                            s.Index = iidx.ToString(CultureInfo.InvariantCulture);
                            iidx++;
                        }
                    }
                }

                ex = 5;
                m.Parts = new List<Part>();
                m.Parts.Add(p);
                bool over = false;
                if (m.Container == "mkv")
                {
                    int val = int.MaxValue;
                    foreach (Stream s in streams)
                    {
                        if (string.IsNullOrEmpty(s.Index))
                        {
                            over = true;
                            break;
                        }
                        s.idx = int.Parse(s.Index);
                        if (s.idx < val)
                            val = s.idx;
                    }
                    if ((val != 0) && (!over))
                    {
                        foreach (Stream s in streams)
                        {
                            s.idx = s.idx - val;
                            s.Index = s.idx.ToString(CultureInfo.InvariantCulture);
                        }
                    }
                    else if (over)
                    {
                        int xx = 0;
                        foreach (Stream s in streams)
                        {
                            s.idx = xx++;
                            s.Index = s.idx.ToString(CultureInfo.InvariantCulture);
                        }
                    }
                    streams = streams.OrderBy(a => a.idx).ToList();
                }
                ex = 6;
                p.Streams = streams;
                if ((p.Container == "mp4") || (p.Container=="mov"))
                {
                    p.Has64bitOffsets = "0";
                    p.OptimizedForStreaming = "0";
                    m.OptimizedForStreaming = "0";
                    byte[] buffer = new byte[8];
                    FileStream fs = File.OpenRead(filename);
                    fs.Read(buffer, 0, 4);
                    int siz = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
                    fs.Seek(siz, SeekOrigin.Begin);
                    fs.Read(buffer, 0, 8);
                    if ((buffer[4] == 'f') && (buffer[5] == 'r') && (buffer[6] == 'e') && (buffer[7] == 'e'))
                    {
                        siz = buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]-8;
                        fs.Seek(siz, SeekOrigin.Current);
                        fs.Read(buffer, 0, 8);
                    }
                    if ((buffer[4] == 'm') && (buffer[5] == 'o') && (buffer[6] == 'o') && (buffer[7] == 'v'))
                    {
                        p.OptimizedForStreaming = "1";
                        m.OptimizedForStreaming = "1";
                        siz = (buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]) - 8;

                        buffer = new byte[siz];
                        fs.Read(buffer, 0, siz);
                        int opos ;
                        int oposmax ;
                        if (FindInBuffer("trak", 0, siz, buffer, out opos, out oposmax))
                        {
                            if (FindInBuffer("mdia", opos, oposmax, buffer, out opos, out oposmax))
                            {
                                if (FindInBuffer("minf", opos, oposmax, buffer, out opos, out oposmax))
                                {

                                    if (FindInBuffer("stbl", opos, oposmax, buffer, out opos, out oposmax))
                                    {
                                        if (FindInBuffer("co64", opos, oposmax, buffer, out opos, out oposmax))
                                        {
                                            p.Has64bitOffsets = "1";
                                        }

                                    }
                                }

                            }
                        }
                    }
                }
                ex = 7;
                return m;
            }
            catch (Exception e)
            {
                throw new Exception(ex+":"+e.Message,e);
                
            }
            finally
            {
                mi.Close();
                GC.Collect();
            }
        }
コード例 #36
0
 public bool OnInfo(MediaPlayer mp, [GeneratedEnum] MediaInfo what, int extra)
 {
     return(true);
 }
コード例 #37
0
ファイル: AudioStream.cs プロジェクト: zetcamp/IFME
 ///<summary>AudioStream constructor.</summary>
 ///<param name="mediaInfo">A MediaInfo object.</param>
 ///<param name="id">The MediaInfo ID for this audio stream.</param>
 public AudioStream(MediaInfo mediaInfo, int id)
     : base(mediaInfo, id)
 {
     kind         = StreamKind.Audio;
     streamCommon = new MultiStreamCommon(mediaInfo, kind, id);
 }
コード例 #38
0
 public async Task IncorrectFormatTest()
 {
     await Assert.ThrowsAsync <ArgumentException>(async() => await MediaInfo.Get(Resources.Dll));
 }
コード例 #39
0
        /// <summary>
        /// Executes the specified param.
        /// </summary>
        /// <param name="param">The param.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public OpResult ExecuteMediaExperience(string param)
        {
            OpResult opResult = new OpResult();

            try
            {
                opResult.StatusCode = OpStatusCode.Success;
                MediaInfo mediaInfo = new MediaInfo();

                //get volume
                mediaInfo.volume   = (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7);
                mediaInfo.is_muted = AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute;

                //get metadata, play_state, play rate and position if available
                if (MediaExperienceWrapper.Instance != null)
                {
                    mediaInfo.metadata     = MediaExperienceWrapper.Instance.MediaMetadata;
                    mediaInfo.play_state   = Enum.GetName(typeof(PlayState), MediaExperienceWrapper.Instance.Transport.PlayState);
                    mediaInfo.play_rate    = Enum.GetName(typeof(Play_Rate_enum), (Int32)MediaExperienceWrapper.Instance.Transport.PlayRate);
                    mediaInfo.position_sec = (Int32)Math.Round(MediaExperienceWrapper.Instance.Transport.Position.TotalSeconds);

                    //search metadata to find type of media and duration
                    Object obj;
                    string objstr, str;
                    if (mediaInfo.metadata.TryGetValue("TrackDuration", out obj))
                    {
                        objstr = obj.ToString();
                        mediaInfo.duration_sec = Convert.ToInt32(objstr);
                        mediaInfo.play_mode    = Enum.GetName(typeof(Play_Mode_enum), Play_Mode_enum.StreamingContentAudio);
                    }
                    else if (mediaInfo.metadata.TryGetValue("Duration", out obj))
                    {
                        TimeSpan ts;
                        objstr = obj.ToString();
                        TimeSpan.TryParse(objstr, out ts);
                        mediaInfo.duration_sec = (Int32)Math.Round(ts.TotalSeconds);
                        if (mediaInfo.metadata.ContainsKey("ChapterTitle"))
                        {
                            mediaInfo.play_mode = Enum.GetName(typeof(Play_Mode_enum), Play_Mode_enum.DVD);
                        }
                        else if (mediaInfo.metadata.TryGetValue("Name", out obj))
                        {
                            objstr = obj.ToString();
                            str    = objstr.ToLower();
                            if (str.EndsWith("dvr_ms") | str.EndsWith("wtv"))
                            {
                                mediaInfo.play_mode = Enum.GetName(typeof(Play_Mode_enum), Play_Mode_enum.PVR);
                            }
                            else
                            {
                                mediaInfo.play_mode = Enum.GetName(typeof(Play_Mode_enum), Play_Mode_enum.StreamingContentVideo);
                            }
                        }
                    }
                }

                //convert times
                mediaInfo.position_hms = TimeSpan.FromSeconds((double)mediaInfo.position_sec);
                mediaInfo.duration_hms = TimeSpan.FromSeconds((double)mediaInfo.duration_sec);

                //flag data as valid
                mediaInfo.info_state = "Valid";

                opResult.ContentObject = mediaInfo;
            }
            catch (Exception ex)
            {
                opResult.StatusCode = OpStatusCode.Exception;
                opResult.StatusText = ex.Message;
            }
            return(opResult);
        }
コード例 #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaOpeningEventArgs" /> class.
 /// </summary>
 /// <param name="options">The options.</param>
 /// <param name="info">The input information.</param>
 public MediaOpeningEventArgs(MediaOptions options, MediaInfo info)
 {
     Options = options;
     Info    = info;
 }
コード例 #41
0
        public ViewMediaInfoForm(string path)
        {
            InitializeComponent();

            Icon = Gui.Icon;

            wb_info.PreviewKeyDown += OnBrowserPreviewKeyDown;

            var mediaFile = new MediaFile(path);
            var mi        = new MediaInfo();

            mi.Open(path);

            var lines = new List <string>();

            {
                lines.Add("<!doctype html>");
                lines.Add("<html>");
                lines.Add("<head>");
                lines.Add("<style>* { padding: 0px; margin: 0px; font-family:tahoma; } body { width: 700px; background: #fff; margin: 0 auto; } table { width: 700px; font-size: 12px; border-collapse: collapse; } td { width: 570px; padding: 5px; border-bottom: 1px dotted #1562b6; word-wrap: break-word; } td:first-child { width: 130px; border-right: 1px solid #1562b6; } .thead { font-size: 15px; color: #1562b6; padding-top: 25px; border: 0px !important; border-bottom: 2px solid #1562b6 !important; } .no-padding { padding-top: 0px !important; }</style>");
                lines.Add("</head>");
                lines.Add("<body>");
                lines.Add("<table border='0' cellspacing='0' cellpadding='0'>");
                lines.Add("<tr><td class='thead no-padding' colspan='2'><b>General</b></td></tr>");
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("UniqueID/String")) ? string.Empty : string.Format("<tr><td>Unique ID:</td><td>{0}</td></tr>", mediaFile.miGetString("UniqueID/String")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Movie")) ? string.Empty : string.Format("<tr><td>Movie name:</td><td>{0}</td></tr>", mediaFile.miGetString("Movie")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("CompleteName")) ? string.Empty : string.Format("<tr><td>Complete name:</td><td>{0}</td></tr>", mediaFile.miGetString("CompleteName")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", mediaFile.miGetString("Format")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Format_Version")) ? string.Empty : string.Format("<tr><td>Format version:</td><td>{0}</td></tr>", mediaFile.miGetString("Format_Version")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("FileSize/String")) ? string.Empty : string.Format("<tr><td>File size:</td><td>{0}</td></tr>", mediaFile.miGetString("FileSize/String")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Duration/String")) ? string.Empty : string.Format("<tr><td>Duration:</td><td>{0}</td></tr>", mediaFile.miGetString("Duration/String")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("OverallBitRate/String")) ? string.Empty : string.Format("<tr><td>Overall bitrate:</td><td>{0}</td></tr>", mediaFile.miGetString("OverallBitRate/String")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Encoded_Date")) ? string.Empty : string.Format("<tr><td>Encoded date:</td><td>{0}</td></tr>", mediaFile.miGetString("Encoded_Date")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Encoded_Application")) ? string.Empty : string.Format("<tr><td>Writing application:</td><td>{0}</td></tr>", mediaFile.miGetString("Encoded_Application")));
                lines.Add(string.IsNullOrEmpty(mediaFile.miGetString("Encoded_Library/String")) ? string.Empty : string.Format("<tr><td>Writing library:</td><td>{0}</td></tr>", mediaFile.miGetString("Encoded_Library/String")));
            }

            lines.Add("<tr><td class='thead' colspan='2'><b>Video</b></td></tr>");
            foreach (var info in mediaFile.Video)
            {
                lines.Add(string.Format("<tr><td>ID:</td><td>{0}</td></tr>", info.Value.miGetString("ID/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Title")) ? string.Empty : string.Format("<tr><td>Title:</td><td>{0}</td></tr>", info.Value.miGetString("Title")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", info.Value.miGetString("Format")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format/Info")) ? string.Empty : string.Format("<tr><td>Format info:</td><td>{0}</td></tr>", info.Value.miGetString("Format/Info")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format_Profile")) ? string.Empty : string.Format("<tr><td>Format profile:</td><td>{0}</td></tr>", info.Value.miGetString("Format_Profile")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format_Settings")) ? string.Empty : string.Format("<tr><td>Format settings:</td><td>{0}</td></tr>", info.Value.miGetString("Format_Settings")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("MuxingMode")) ? string.Empty : string.Format("<tr><td>Muxing mode:</td><td>{0}</td></tr>", info.Value.miGetString("MuxingMode")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID/String")) ? string.Empty : string.Format("<tr><td>Codec ID:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Duration/String")) ? string.Empty : string.Format("<tr><td>Duration:</td><td>{0}</td></tr>", info.Value.miGetString("Duration/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate/String")) ? string.Empty : string.Format("<tr><td>Bitrate:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate_Nominal/String")) ? string.Empty : string.Format("<tr><td>Nominal bitrate:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate_Nominal/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Width/String")) ? string.Empty : string.Format("<tr><td>Width:</td><td>{0}</td></tr>", info.Value.miGetString("Width/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Height/String")) ? string.Empty : string.Format("<tr><td>Height:</td><td>{0}</td></tr>", info.Value.miGetString("Height/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("DisplayAspectRatio/String")) ? string.Empty : string.Format("<tr><td>Display aspect ratio:</td><td>{0}</td></tr>", info.Value.miGetString("DisplayAspectRatio/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("FrameRate_Mode/String")) ? string.Empty : string.Format("<tr><td>Frame rate mode:</td><td>{0}</td></tr>", info.Value.miGetString("FrameRate_Mode/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("FrameRate/String")) ? string.Empty : string.Format("<tr><td>Frame rate:</td><td>{0}</td></tr>", info.Value.miGetString("FrameRate/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("ColorSpace")) ? string.Empty : string.Format("<tr><td>Color space:</td><td>{0}</td></tr>", info.Value.miGetString("ColorSpace")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("ChromaSubsampling")) ? string.Empty : string.Format("<tr><td>Chroma subsampling:</td><td>{0}</td></tr>", info.Value.miGetString("ChromaSubsampling")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitDepth/String")) ? string.Empty : string.Format("<tr><td>Bit depth:</td><td>{0}</td></tr>", info.Value.miGetString("BitDepth/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("ScanType")) ? string.Empty : string.Format("<tr><td>Scan type:</td><td>{0}</td></tr>", info.Value.miGetString("ScanType")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Bits-(Pixel*Frame)")) ? string.Empty : string.Format("<tr><td>Bits/(Pixel*Frame):</td><td>{0}</td></tr>", info.Value.miGetString("Bits-(Pixel*Frame)")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("StreamSize/String")) ? string.Empty : string.Format("<tr><td>Stream size:</td><td>{0}</td></tr>", info.Value.miGetString("StreamSize/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Encoded_Library/String")) ? string.Empty : string.Format("<tr><td>Writing library:</td><td>{0}</td></tr>", info.Value.miGetString("Encoded_Library/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Encoded_Library_Settings")) ? string.Empty : string.Format("<tr><td>Encoding settings:</td><td>{0}</td></tr>", info.Value.miGetString("Encoded_Library_Settings")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Language/String")) ? string.Empty : string.Format("<tr><td>Language:</td><td>{0}</td></tr>", info.Value.miGetString("Language/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Default/String")) ? string.Empty : string.Format("<tr><td>Default:</td><td>{0}</td></tr>", info.Value.miGetString("Default/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Forced/String")) ? string.Empty : string.Format("<tr><td>Forced:</td><td>{0}</td></tr>", info.Value.miGetString("Forced/String")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("colour_range")) ? string.Empty : string.Format("<tr><td>Color range:</td><td>{0}</td></tr>", info.Value.miGetString("colour_range")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("colour_primaries")) ? string.Empty : string.Format("<tr><td>Color primaries:</td><td>{0}</td></tr>", info.Value.miGetString("colour_primaries")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("transfer_characteristics")) ? string.Empty : string.Format("<tr><td>Transfer characteristics:</td><td>{0}</td></tr>", info.Value.miGetString("transfer_characteristics")));
                lines.Add(string.IsNullOrEmpty(info.Value.miGetString("matrix_coefficients")) ? string.Empty : string.Format("<tr><td>Matrix coefficients:</td><td>{0}</td></tr>", info.Value.miGetString("matrix_coefficients")));
            }

            if (mediaFile.Audio.Count > 0)
            {
                int audioTracks = 1;

                foreach (var info in mediaFile.Audio)
                {
                    lines.Add(mediaFile.Audio.Count == 1 ? "<tr><td class='thead' colspan='2'><b>Audio</b></td></tr>" : string.Format("<tr><td class='thead' colspan='2'><b>Audio #{0}</b></td></tr>", audioTracks));
                    lines.Add(string.Format("<tr><td>ID:</td><td>{0}</td></tr>", info.Value.miGetString("ID/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Title")) ? string.Empty : string.Format("<tr><td>Title:</td><td>{0}</td></tr>", info.Value.miGetString("Title")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", info.Value.miGetString("Format")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format/Info")) ? string.Empty : string.Format("<tr><td>Format info:</td><td>{0}</td></tr>", info.Value.miGetString("Format/Info")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID/String")) ? string.Empty : string.Format("<tr><td>Codec ID:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Duration/String")) ? string.Empty : string.Format("<tr><td>Duration:</td><td>{0}</td></tr>", info.Value.miGetString("Duration/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate_Mode/String")) ? string.Empty : string.Format("<tr><td>Bitrate mode:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate_Mode/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitRate/String")) ? string.Empty : string.Format("<tr><td>Bitrate:</td><td>{0}</td></tr>", info.Value.miGetString("BitRate/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Channel(s)/String")) ? string.Empty : string.Format("<tr><td>Channels:</td><td>{0}</td></tr>", info.Value.miGetString("Channel(s)/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("SamplingRate/String")) ? string.Empty : string.Format("<tr><td>Sampling rate:</td><td>{0}</td></tr>", info.Value.miGetString("SamplingRate/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("BitDepth/String")) ? string.Empty : string.Format("<tr><td>Bit depth:</td><td>{0}</td></tr>", info.Value.miGetString("BitDepth/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Compression_Mode/String")) ? string.Empty : string.Format("<tr><td>Compression mode:</td><td>{0}</td></tr>", info.Value.miGetString("Compression_Mode/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("StreamSize/String")) ? string.Empty : string.Format("<tr><td>Stream size:</td><td>{0}</td></tr>", info.Value.miGetString("StreamSize/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Language/String")) ? string.Empty : string.Format("<tr><td>Language:</td><td>{0}</td></tr>", info.Value.miGetString("Language/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Default/String")) ? string.Empty : string.Format("<tr><td>Default:</td><td>{0}</td></tr>", info.Value.miGetString("Default/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Forced/String")) ? string.Empty : string.Format("<tr><td>Forced:</td><td>{0}</td></tr>", info.Value.miGetString("Forced/String")));

                    audioTracks++;
                }
            }

            if (mediaFile.Text.Count > 0)
            {
                int textTracks = 1;

                foreach (var info in mediaFile.Text)
                {
                    lines.Add(mediaFile.Text.Count == 1 ? "<tr><td class='thead' colspan='2'><b>Text</b></td></tr>" : string.Format("<tr><td class='thead' colspan='2'><b>Text #{0}</b></td></tr>", textTracks));
                    lines.Add(string.Format("<tr><td>ID:</td><td>{0}</td></tr>", info.Value.miGetString("ID/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Format")) ? string.Empty : string.Format("<tr><td>Format:</td><td>{0}</td></tr>", info.Value.miGetString("Format")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID")) ? string.Empty : string.Format("<tr><td>Codec ID:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("CodecID/Info")) ? string.Empty : string.Format("<tr><td>Codec ID info:</td><td>{0}</td></tr>", info.Value.miGetString("CodecID/Info")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Compression_Mode/String")) ? string.Empty : string.Format("<tr><td>Compression mode:</td><td>{0}</td></tr>", info.Value.miGetString("Compression_Mode/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Language/String")) ? string.Empty : string.Format("<tr><td>Language:</td><td>{0}</td></tr>", info.Value.miGetString("Language/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Default/String")) ? string.Empty : string.Format("<tr><td>Default:</td><td>{0}</td></tr>", info.Value.miGetString("Default/String")));
                    lines.Add(string.IsNullOrEmpty(info.Value.miGetString("Forced/String")) ? string.Empty : string.Format("<tr><td>Forced:</td><td>{0}</td></tr>", info.Value.miGetString("Forced/String")));

                    textTracks++;
                }
            }

            if (mediaFile.Menu.Count > 0)
            {
                int chapterBegin = int.Parse(mi.Get(StreamKind.Menu, 0, "Chapters_Pos_Begin"));
                int chapterEnd   = int.Parse(mi.Get(StreamKind.Menu, 0, "Chapters_Pos_End"));

                lines.Add("<tr><td class='thead' colspan='2'><b>Menu</b></td></tr>");
                foreach (var info in mediaFile.Menu)
                {
                    for (int i = chapterBegin; i < chapterEnd; i++)
                    {
                        string key   = mi.Get(StreamKind.Menu, 0, i, InfoKind.Name);
                        string value = mi.Get(StreamKind.Menu, 0, i);
                        lines.Add(string.IsNullOrEmpty(info.Value.miGetString(key)) ? string.Empty : string.Format("<tr><td>{0}:</td><td>{1}</td></tr>", key, value));
                    }
                }
            }

            lines.Add("</table></body></html>");

            wb_info.DocumentText = string.Join("\n", lines.ToArray());
        }
コード例 #42
0
ファイル: MenuStream.cs プロジェクト: Mouaijin/DownloadSort
 ///<summary>MenuStream constructor.</summary>
 ///<param name="mediaInfo">A MediaInfo object which has already opened a media file.</param>
 ///<param name="id">The MediaInfo ID for this menu stream.</param>
 public MenuStream(MediaInfo mediaInfo, int id)
     : base(mediaInfo, StreamKind.Menu, id)
 {
 }
コード例 #43
0
ファイル: Player.cs プロジェクト: avblocks/avblocks-samples
        public bool Open(string filePath)
        {
            Close();

            if (!ConfigureStreams(filePath))
            {
                Close();
                return(false);
            }

            _transcoder = new Transcoder();
            // In order to use the OEM release for testing (without a valid license) the transcoder demo mode must be enabled.
            _transcoder.AllowDemoMode = true;

            // Configure input
            {
                using (MediaInfo mediaInfo = new MediaInfo())
                {
                    mediaInfo.Inputs[0].File = filePath;

                    if (!(mediaInfo.Open()))
                    {
                        return(false);
                    }

                    MediaSocket socket = MediaSocket.FromMediaInfo(mediaInfo);
                    _transcoder.Inputs.Add(socket);
                }
            }

            // Configure video output
            if (_videoStreamInfo != null)
            {
                _videoStreamInfo.ColorFormat   = ColorFormat.BGR24;
                _videoStreamInfo.FrameBottomUp = true;
                _videoStreamInfo.StreamType    = StreamType.UncompressedVideo;
                _videoStreamInfo.ScanType      = ScanType.Progressive;

                MediaPin pin = new MediaPin();

                int displayWidth  = Screen.PrimaryScreen.Bounds.Width;
                int displayHeight = Screen.PrimaryScreen.Bounds.Height;

                if ((_videoStreamInfo.FrameWidth > displayWidth) ||
                    ((_videoStreamInfo.FrameHeight > displayHeight)))
                {
                    // resize the video
                    double displayAspect = (double)displayWidth / (double)displayHeight;
                    double videoAspect   = (double)_videoStreamInfo.DisplayRatioWidth / (double)_videoStreamInfo.DisplayRatioHeight;

                    int width  = 0;
                    int height = 0;

                    if (videoAspect < displayAspect)
                    {
                        width  = displayWidth;
                        height = (int)(displayWidth / videoAspect);
                    }
                    else
                    {
                        width  = (int)(displayHeight * videoAspect);
                        height = displayHeight;
                    }

                    width  += calculatePadding(width, 2);
                    height += calculatePadding(height, 2);

                    _videoStreamInfo.FrameWidth  = width;
                    _videoStreamInfo.FrameHeight = height;

                    {
                        pin.Params.Add(Param.Video.Resize.InterpolationMethod, PrimoSoftware.AVBlocks.InterpolationMethod.Linear);
                    }
                }

                pin.StreamInfo = _videoStreamInfo;

                MediaSocket socket = new MediaSocket();
                socket.StreamType = StreamType.UncompressedVideo;
                socket.Pins.Add(pin);

                _videoStreamIndex = _transcoder.Outputs.Count;
                _transcoder.Outputs.Add(socket);
            }

            // Configure audio output
            if (_audioStreamInfo != null)
            {
                _audioStreamInfo.BitsPerSample = 16;

                // WinMM audio render supports only mono and stereo
                if (_audioStreamInfo.Channels > 2)
                {
                    _audioStreamInfo.Channels = 2;
                }

                _audioStreamInfo.StreamType = StreamType.LPCM;

                MediaPin pin = new MediaPin();
                pin.StreamInfo = _audioStreamInfo;

                MediaSocket socket = new MediaSocket();
                socket.StreamType = StreamType.LPCM;
                socket.Pins.Add(pin);

                _audioStreamIndex = _transcoder.Outputs.Count;
                _transcoder.Outputs.Add(socket);
            }

            if (!_transcoder.Open())
            {
                Close();
                return(false);
            }

            return(true);
        }
コード例 #44
0
ファイル: Main.cs プロジェクト: fossabot/DiscImageChef
        public static void Main(string[] args)
        {
            DicConsole.WriteLineEvent      += System.Console.WriteLine;
            DicConsole.WriteEvent          += System.Console.Write;
            DicConsole.ErrorWriteLineEvent += System.Console.Error.WriteLine;

            Settings.Settings.LoadSettings();
            if (Settings.Settings.Current.GdprCompliance < DicSettings.GdprLevel)
            {
                Configure.DoConfigure(true);
            }
            Statistics.LoadStats();
            if (Settings.Settings.Current.Stats != null && Settings.Settings.Current.Stats.ShareStats)
            {
                Statistics.SubmitStats();
            }

            Parser.Default.ParseArguments(args, typeof(AnalyzeOptions), typeof(BenchmarkOptions),
                                          typeof(ChecksumOptions), typeof(CompareOptions), typeof(ConfigureOptions),
                                          typeof(ConvertImageOptions), typeof(CreateSidecarOptions),
                                          typeof(DecodeOptions), typeof(DeviceInfoOptions), typeof(DeviceReportOptions),
                                          typeof(DumpMediaOptions), typeof(EntropyOptions), typeof(ExtractFilesOptions),
                                          typeof(FormatsOptions), typeof(ImageInfoOptions), typeof(ListDevicesOptions),
                                          typeof(ListEncodingsOptions), typeof(ListOptionsOptions), typeof(LsOptions),
                                          typeof(MediaInfoOptions), typeof(MediaScanOptions), typeof(PrintHexOptions),
                                          typeof(StatsOptions), typeof(VerifyOptions), typeof(GuiOptions))
            .WithParsed <AnalyzeOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Analyze.DoAnalyze(opts);
            }).WithParsed <CompareOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Compare.DoCompare(opts);
            }).WithParsed <ChecksumOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Checksum.DoChecksum(opts);
            }).WithParsed <EntropyOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Entropy.DoEntropy(opts);
            }).WithParsed <VerifyOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Verify.DoVerify(opts);
            }).WithParsed <PrintHexOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Commands.PrintHex.DoPrintHex(opts);
            }).WithParsed <DecodeOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Decode.DoDecode(opts);
            }).WithParsed <DeviceInfoOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                DeviceInfo.DoDeviceInfo(opts);
            }).WithParsed <MediaInfoOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                MediaInfo.DoMediaInfo(opts);
            }).WithParsed <MediaScanOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                MediaScan.DoMediaScan(opts);
            }).WithParsed <FormatsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Formats.ListFormats(opts);
            }).WithParsed <BenchmarkOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Benchmark.DoBenchmark(opts);
            }).WithParsed <CreateSidecarOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                CreateSidecar.DoSidecar(opts);
            }).WithParsed <DumpMediaOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                DumpMedia.DoDumpMedia(opts);
            }).WithParsed <DeviceReportOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                DeviceReport.DoDeviceReport(opts);
            }).WithParsed <LsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                Ls.DoLs(opts);
            }).WithParsed <ExtractFilesOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ExtractFiles.DoExtractFiles(opts);
            }).WithParsed <ListDevicesOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ListDevices.DoListDevices(opts);
            }).WithParsed <ListEncodingsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ListEncodings.DoList();
            }).WithParsed <ListOptionsOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ListOptions.DoList();
            }).WithParsed <ConvertImageOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ConvertImage.DoConvert(opts);
            }).WithParsed <ImageInfoOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }
                PrintCopyright();
                ImageInfo.GetImageInfo(opts);
            }).WithParsed <ConfigureOptions>(opts =>
            {
                PrintCopyright();
                Configure.DoConfigure(false);
            }).WithParsed <StatsOptions>(opts =>
            {
                PrintCopyright();
                Commands.Statistics.ShowStats();
            }).WithParsed <GuiOptions>(opts =>
            {
                if (opts.Debug)
                {
                    DicConsole.DebugWriteLineEvent += System.Console.Error.WriteLine;
                }
                if (opts.Verbose)
                {
                    DicConsole.VerboseWriteLineEvent += System.Console.WriteLine;
                }

                new Application(Platform.Detect).Run(new frmMain(opts.Debug, opts.Verbose));
            }).WithNotParsed(errs => Environment.Exit(1));

            Statistics.SaveStats();
        }
コード例 #45
0
ファイル: ImageStream.cs プロジェクト: Mouaijin/DownloadSort
 ///<summary>ImageStream constructor.</summary>
 ///<param name="mediaInfo">A MediaInfo object.</param>
 ///<param name="id">The MediaInfo ID for this image stream.</param>
 public ImageStream(MediaInfo mediaInfo, int id)
     : base(mediaInfo, StreamKind.Image, id)
 {
 }
コード例 #46
0
 ///<summary>VideoStream constructor</summary>
 ///<param name="mediaInfo">A MediaInfo object.</param>
 ///<param name="id">The MediaInfo ID for this audio stream.</param>
 public VideoStream(MediaInfo mediaInfo, int id)
     : base(mediaInfo, StreamKind.Video, id)
 {
 }
コード例 #47
0
 public Task Update(MediaInfo mediaInfo, byte[] data)
 {
     return Create(mediaInfo, data);
 }
コード例 #48
0
        /// <summary>
        /// Show the media information
        /// </summary>
        /// <param name="mParams">MediaInfoFormParams object</param>
        public void ShowMediaInfo(object mParams)
        {
            MediaInfoFormParams mediaParams = (MediaInfoFormParams)mParams;
            string    sourceVideo           = mediaParams.sourceVideo;
            MediaInfo mediaInfo             = mediaParams.mediaInfo;
            ToolTip   toolTip = mediaParams.toolTip;

            // Video Name
            mediaSpace.SelectionAlignment = HorizontalAlignment.Center;
            mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
            mediaSpace.AppendText(Path.GetFileName(sourceVideo) + "\n");
            mediaSpace.SelectionFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2)));

            // Video information
            TimeSpan t        = TimeSpan.FromSeconds(mediaInfo.VideoInfo.Duration);
            string   duration = string.Format("{0:D2}h : {1:D2}m : {2:D2}s",
                                              t.Hours,
                                              t.Minutes,
                                              t.Seconds);

            mediaSpace.AppendText("\n");
            mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
            mediaSpace.SelectionAlignment = HorizontalAlignment.Center;
            mediaSpace.AppendText(Localise.GetPhrase("Video") + "\n");
            mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
            mediaSpace.SelectionAlignment = HorizontalAlignment.Left;
            mediaSpace.AppendText("------------------------------------------------------------------------------");
            mediaSpace.AppendText("\n" + Localise.GetPhrase("Codec") + "\t  :  " + mediaInfo.VideoInfo.VideoCodec);
            mediaSpace.AppendText("\n" + Localise.GetPhrase("Duration") + "\t  :  " + duration);
            mediaSpace.AppendText("\n" + Localise.GetPhrase("Height") + "\t  :  " + mediaInfo.VideoInfo.Height.ToString().Replace("-1", "-"));
            mediaSpace.AppendText("\n" + Localise.GetPhrase("Width") + "\t  :  " + mediaInfo.VideoInfo.Width.ToString().Replace("-1", "-"));
            mediaSpace.AppendText("\n" + Localise.GetPhrase("FPS") + "\t  :  " + mediaInfo.VideoInfo.FPS.ToString(System.Globalization.CultureInfo.InvariantCulture));

            // Audio Information
            if (mediaInfo.AudioInfo != null)
            {
                for (int i = 0; i < mediaInfo.AudioInfo.Count; i++)
                {
                    mediaSpace.AppendText("\n\n");
                    mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
                    mediaSpace.SelectionAlignment = HorizontalAlignment.Center;
                    mediaSpace.AppendText(Localise.GetPhrase("Audio") + " " + (i + 1).ToString() + "\n");
                    mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
                    mediaSpace.SelectionAlignment = HorizontalAlignment.Left;
                    mediaSpace.AppendText("------------------------------------------------------------------------------");
                    try
                    {
                        mediaSpace.AppendText(Localise.GetPhrase("Language") + " :  " + ISO639_3.GetLanguageName(mediaInfo.AudioInfo[i].Language));
                        if (!String.IsNullOrEmpty(mediaInfo.AudioInfo[i].Language))
                        {
                            mediaSpace.AppendText("  (" + mediaInfo.AudioInfo[i].Language + ")");
                        }
                        if (mediaInfo.AudioInfo[i].Impaired)
                        {
                            mediaSpace.AppendText("  (" + Localise.GetPhrase("Impaired") + ")");
                        }
                    }
                    catch
                    {
                        mediaSpace.AppendText(Localise.GetPhrase("Language") + " :  " + Localise.GetPhrase("Unknown")); // Exception thrown if the language code is not known
                        if (mediaInfo.AudioInfo[i].Impaired)
                        {
                            mediaSpace.AppendText("  (" + Localise.GetPhrase("Impaired") + ")");
                        }
                    }
                    mediaSpace.AppendText("\n" + Localise.GetPhrase("Codec") + "\t :  " + mediaInfo.AudioInfo[i].AudioCodec);
                    mediaSpace.AppendText("\n" + Localise.GetPhrase("Channels") + "  :  " + mediaInfo.AudioInfo[i].Channels.ToString().Replace("-1", "-"));
                }
            }

            // Subtitle Information - no need to show, we don't use it in MCEBuddy
            if (mediaInfo.SubtitleInfo != null)
            {
                for (int i = 0; i < mediaInfo.SubtitleInfo.Count; i++)
                {
                    mediaSpace.AppendText("\n\n");
                    mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
                    mediaSpace.SelectionAlignment = HorizontalAlignment.Center;
                    mediaSpace.AppendText(Localise.GetPhrase("Subtitle") + " " + (i + 1).ToString() + "\n");
                    mediaSpace.SelectionFont      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2)));
                    mediaSpace.SelectionAlignment = HorizontalAlignment.Left;
                    mediaSpace.AppendText("------------------------------------------------------------------------------");

                    try
                    {
                        mediaSpace.AppendText(Localise.GetPhrase("Language") + " :  " + ISO639_3.GetLanguageName(mediaInfo.SubtitleInfo[i].Language));
                        if (!String.IsNullOrEmpty(mediaInfo.SubtitleInfo[i].Language))
                        {
                            mediaSpace.AppendText("  (" + mediaInfo.SubtitleInfo[i].Language + ")");
                        }
                    }
                    catch
                    {
                        mediaSpace.AppendText(Localise.GetPhrase("Language") + " :  " + Localise.GetPhrase("Unknown")); // Exception thrown if the language code is not known
                    }
                    mediaSpace.AppendText("\n" + Localise.GetPhrase("Codec") + "\t :  " + mediaInfo.SubtitleInfo[i].Name);
                }
            }

            mediaSpace.Height = 170 + 78 * (mediaInfo.AudioInfo == null ? 0 : mediaInfo.AudioInfo.Count) + 60 * (mediaInfo.SubtitleInfo == null ? 0 : mediaInfo.SubtitleInfo.Count); // Name+Video 170, Audio 75, Subtitle 60 each
            this.Height       = mediaSpace.Bottom + 10;                                                                                                                              // Window height buffer from edge
            LocaliseForms.LocaliseForm(this, toolTip);                                                                                                                               // Localize the Text
            ShowDialog();
            Focus();

            return;
        }
コード例 #49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MediaStreamBuilder{TStream}"/> class.
 /// </summary>
 /// <param name="info">The media info object.</param>
 /// <param name="number">The stream number.</param>
 /// <param name="position">The stream position.</param>
 protected MediaStreamBuilder(MediaInfo info, int number, int position)
 {
     Info           = info;
     StreamNumber   = number;
     StreamPosition = position;
 }
コード例 #50
0
        public void WriteMediaTSPacket(TSPacket pack)
        {
            // Console.WriteLine(pack.PID);
            var data         = pack.data;
            var newFrameFlag = data[0] == 0x0 && data[1] == 0x0 && data[2] == 0x1 && (data[3] == 0xE0 || data[3] == 0xC0);

            MediaInfo mi = null;

            lock (_dicMediaFrameCache) {
                if (_dicMediaFrameCache.ContainsKey(pack.PID))
                {
                    mi = _dicMediaFrameCache[pack.PID];
                }
                else
                {
                    if (newFrameFlag)
                    {
                        _dicMediaFrameCache[pack.PID] = mi = new MediaInfo()
                        {
                            PID     = pack.PID,
                            IsVideo = pack.data[3] == 0xE0,
                            IsAudio = pack.data[3] == 0xC0,
                        };
                    }
                }
            }
            if (mi != null)
            {
                if (newFrameFlag)
                {
                    lock (mi.TSPackets) {
                        if ((mi.IsAudio && pack.data[3] != 0xC0) || (mi.IsVideo && pack.data[3] != 0xE0))
                        {
                            lock (_dicMediaFrameCache) {
                                foreach (var item in _dicMediaFrameCache.Values)
                                {
                                    item.Release();
                                }
                                _dicMediaFrameCache.Clear();
                            }
                            return;
                        }

                        var mediaFrame = mi.NextMediaFrame();

                        if (mediaFrame != null && mediaFrame.nSize == mediaFrame.Data.Length)
                        {
                            OnNewMediaFrame(mediaFrame);
                        }

                        mi.TSPackets.Clear();

                        mi.TSPackets.Add(pack);
                    }
                }
                else
                {
                    lock (mi.TSPackets)
                        mi.TSPackets.Add(pack);
                }
            }
        }
コード例 #51
0
ファイル: Convert.cs プロジェクト: maz0r/jmmserver
        private static Stream TranslateVideoStream(MediaInfo m, int num)
        {
            Stream s=new Stream();
            s.Id = m.Get(StreamKind.Video,num,"UniqueID");
            s.Codec = TranslateCodec(m.Get(StreamKind.Video, num, "Codec"));
            s.CodecID = (m.Get(StreamKind.Video, num, "CodecID"));
            s.StreamType = "1";
            s.Width = m.Get(StreamKind.Video, num, "Width");
            string title = m.Get(StreamKind.Video, num, "Title");
            if (!string.IsNullOrEmpty(title))
                s.Title = title;

            string lang = m.Get(StreamKind.Video, num, "Language/String3");
            if (!string.IsNullOrEmpty(lang))
                s.LanguageCode = PostTranslateCode3(lang);
            string lan = PostTranslateLan(GetLanguageFromCode3(lang, m.Get(StreamKind.Video, num, "Language/String1")));
            if (!string.IsNullOrEmpty(lan))
                s.Language = lan;
            string duration = m.Get(StreamKind.Video, num, "Duration");
            if (!string.IsNullOrEmpty(duration))
                s.Duration = duration;
            s.Height = m.Get(StreamKind.Video, num, "Height");
            int brate = BiggerFromList(m.Get(StreamKind.Video, num, "BitRate"));
            if (brate!=0)
                s.Bitrate = Math.Round(brate / 1000F).ToString(CultureInfo.InvariantCulture);
            string stype = m.Get(StreamKind.Video, num, "ScanType");
            if (!string.IsNullOrEmpty(stype))
                s.ScanType=stype.ToLower();
            string refframes = m.Get(StreamKind.Video, num, "Format_Settings_RefFrames");
            if (!string.IsNullOrEmpty(refframes))
                s.RefFrames = refframes;
            string fprofile = m.Get(StreamKind.Video, num, "Format_Profile");
            if (!string.IsNullOrEmpty(fprofile))
            {
                int a = fprofile.ToLower(CultureInfo.InvariantCulture).IndexOf("@", StringComparison.Ordinal);
                if (a > 0)
                {
                    s.Profile = TranslateProfile(s.Codec,fprofile.ToLower(CultureInfo.InvariantCulture).Substring(0, a));
                    s.Level = TranslateLevel(fprofile.ToLower(CultureInfo.InvariantCulture).Substring(a + 1));
                }
                else
                    s.Profile = TranslateProfile(s.Codec, fprofile.ToLower(CultureInfo.InvariantCulture));
            }
            string rot = m.Get(StreamKind.Video, num, "Rotation");
            
            if (!string.IsNullOrEmpty(rot))
            {
                float val;
                if (float.TryParse(rot, out val))
                {
                    if (val == 90F)
                        s.Orientation = "9";
                    else if (val == 180F)
                        s.Orientation = "3";
                    else if (val == 270F)
                        s.Orientation = "6";
                }
                else
                    s.Orientation = rot;
            }
            string muxing = m.Get(StreamKind.Video, num, "MuxingMode");
            if (!string.IsNullOrEmpty(muxing))
            {
                if (muxing.ToLower(CultureInfo.InvariantCulture).Contains("strip"))
                    s.HeaderStripping = "1";
            }
             string cabac = m.Get(StreamKind.Video, num, "Format_Settings_CABAC");
            if (!string.IsNullOrEmpty(cabac))
            {
                s.Cabac = cabac.ToLower(CultureInfo.InvariantCulture) == "yes" ? "1" : "0";
            }
            if (s.Codec=="h264")
            {
                if (!string.IsNullOrEmpty(s.Level) && (s.Level=="31") && (s.Cabac==null || s.Cabac=="0"))
                    s.HasScalingMatrix = "1";
                else
                    s.HasScalingMatrix = "0";
            }
            string fratemode = m.Get(StreamKind.Video, num, "FrameRate_Mode");
            if (!string.IsNullOrEmpty(fratemode))
                s.FrameRateMode = fratemode.ToLower(CultureInfo.InvariantCulture);
            float frate = m.GetFloat(StreamKind.Video, num, "FrameRate");
            if (frate==0.0F)
                frate = m.GetFloat(StreamKind.Video, num, "FrameRate_Original");
            if (frate != 0.0F)
                s.FrameRate=frate.ToString("F3");
            string colorspace = m.Get(StreamKind.Video, num, "ColorSpace");
            if (!string.IsNullOrEmpty(colorspace))
                s.ColorSpace=colorspace.ToLower(CultureInfo.InvariantCulture);
            string chromasubsampling= m.Get(StreamKind.Video, num, "ChromaSubsampling");
            if (!string.IsNullOrEmpty(chromasubsampling))
                s.ChromaSubsampling=chromasubsampling.ToLower(CultureInfo.InvariantCulture);


            int bitdepth = m.GetInt(StreamKind.Video, num, "BitDepth");
            if (bitdepth != 0)
                s.BitDepth = bitdepth.ToString(CultureInfo.InvariantCulture);
            string id = m.Get(StreamKind.Video, num, "ID");
            if (!string.IsNullOrEmpty(id))
            {
                int idx;
                if (int.TryParse(id, out idx))
                {
                    s.Index = idx.ToString(CultureInfo.InvariantCulture);
                }
            }
            string qpel = m.Get(StreamKind.Video, num, "Format_Settings_QPel");
            if (!string.IsNullOrEmpty(qpel))
            {
                s.QPel = qpel.ToLower(CultureInfo.InvariantCulture) == "yes" ? "1" : "0";
            }
            string gmc = m.Get(StreamKind.Video, num, "Format_Settings_GMC");
            if (!string.IsNullOrEmpty(gmc))
            {
                s.GMC = gmc;
            }
            string bvop = m.Get(StreamKind.Video, num, "Format_Settings_BVOP");
            if (!string.IsNullOrEmpty(bvop) && (s.Codec!="mpeg1video"))
            {
                if (bvop == "No")
                    s.BVOP = "0";
                else if ((bvop == "1") || (bvop=="Yes"))
                    s.BVOP = "1";
            }
            string def = m.Get(StreamKind.Text, num, "Default");
            if (!string.IsNullOrEmpty(def))
            {
                if (def.ToLower(CultureInfo.InvariantCulture) == "yes")
                    s.Default = "1";
            }
            string forced = m.Get(StreamKind.Text, num, "Forced");
            if (!string.IsNullOrEmpty(forced))
            {
                if (forced.ToLower(CultureInfo.InvariantCulture) == "yes")
                    s.Forced = "1";
            }
            s.PA = m.GetFloat(StreamKind.Video, num, "PixelAspectRatio");
            string sp2 = m.Get(StreamKind.Video, num, "PixelAspectRatio_Original");
            if (!string.IsNullOrEmpty(sp2))
                s.PA = System.Convert.ToSingle(sp2);
            if ((s.PA != 1.0) && (!string.IsNullOrEmpty(s.Width)))
            {
                float width = int.Parse(s.Width);
                width *= s.PA;
                s.PixelAspectRatio=((int)Math.Round(width)).ToString(CultureInfo.InvariantCulture)+":"+s.Width;
            }

            return s;
        }
コード例 #52
0
 public AudioStreamBuilder(MediaInfo info, int number, int position)
     : base(info, number, position)
 {
 }
コード例 #53
0
ファイル: Convert.cs プロジェクト: maz0r/jmmserver
        private static Stream TranslateTextStream(MediaInfo m, int num)
        {
            Stream s = new Stream();


            s.Id = m.Get(StreamKind.Text, num, "UniqueID");
            s.CodecID = (m.Get(StreamKind.Text, num, "CodecID"));

            s.StreamType = "3";
            string title = m.Get(StreamKind.Text, num, "Title");
            if (!string.IsNullOrEmpty(title))
                s.Title = title;

            string lang = m.Get(StreamKind.Text, num, "Language/String3");
            if (!string.IsNullOrEmpty(lang))
                s.LanguageCode = PostTranslateCode3(lang);
            string lan = PostTranslateLan(GetLanguageFromCode3(lang, m.Get(StreamKind.Text, num, "Language/String1")));
            if (!string.IsNullOrEmpty(lan))
                s.Language = lan;
            string id = m.Get(StreamKind.Text, num, "ID");
            if (!string.IsNullOrEmpty(id))
            {
                int idx ;
                if (int.TryParse(id, out idx))
                {
                    s.Index = idx.ToString(CultureInfo.InvariantCulture);
                }
            }
            s.Format = s.Codec=GetFormat(m.Get(StreamKind.Text, num, "CodecID"), m.Get(StreamKind.Text, num, "Format"));

            string def = m.Get(StreamKind.Text, num, "Default");
            if (!string.IsNullOrEmpty(def))
            {
                if (def.ToLower(CultureInfo.InvariantCulture) == "yes")
                    s.Default = "1";
            }
            string forced = m.Get(StreamKind.Text, num, "Forced");
            if (!string.IsNullOrEmpty(forced))
            {
                if (forced.ToLower(CultureInfo.InvariantCulture) == "yes")
                    s.Forced = "1";
            }


            return s;
        }
コード例 #54
0
        public MediaInfoWrapper(string strFile)
        {
            bool isTV       = MediaPortal.Util.Utils.IsLiveTv(strFile);
            bool isRadio    = MediaPortal.Util.Utils.IsLiveRadio(strFile);
            bool isDVD      = MediaPortal.Util.Utils.IsDVD(strFile);
            bool isVideo    = MediaPortal.Util.Utils.IsVideo(strFile);
            bool isAVStream = MediaPortal.Util.Utils.IsAVStream(strFile); //rtsp users for live TV and recordings.

            if (isTV || isRadio || isAVStream)
            {
                return;
            }

            try
            {
                _mI = new MediaInfo();
                _mI.Open(strFile);

                FileInfo  fileInfo  = strFile.PathToFileInfo();
                DriveInfo driveInfo = fileInfo.GetDriveInfo();

                NumberFormatInfo providerNumber = new NumberFormatInfo();
                providerNumber.NumberDecimalSeparator = ".";

                double.TryParse(_mI.Get(StreamKind.Video, 0, "FrameRate"), NumberStyles.AllowDecimalPoint, providerNumber, out _framerate);
                _videoCodec = _mI.Get(StreamKind.Video, 0, "Codec").ToLower();
                _scanType   = _mI.Get(StreamKind.Video, 0, "ScanType").ToLower();
                int.TryParse(_mI.Get(StreamKind.Video, 0, "Width"), out _width);
                int.TryParse(_mI.Get(StreamKind.Video, 0, "Height"), out _height);
                int.TryParse(_mI.Get(StreamKind.General, 0, "TextCount"), out _numSubtitles);
                int intValue;
                int iAudioStreams = _mI.Count_Get(StreamKind.Audio);
                for (int i = 0; i < iAudioStreams; i++)
                {
                    string sChannels = Regex.Split(_mI.Get(StreamKind.Audio, i, "Channel(s)"), @"\D+").Max();


                    if (int.TryParse(sChannels, out intValue) && intValue > _audioChannels)
                    {
                        _audioChannels = intValue;
                        int.TryParse(_mI.Get(StreamKind.Audio, i, "SamplingRate"), out _audioRate);
                        _audioCodec         = _mI.Get(StreamKind.Audio, i, "Codec/String").ToLower();
                        _audioFormatProfile = _mI.Get(StreamKind.Audio, i, "Format_Profile").ToLower();
                    }
                }

                string aspectStr = _mI.Get(StreamKind.Video, 0, "AspectRatio/String");
                if (aspectStr == "4/3" || aspectStr == "4:3")
                {
                    _aspectRatio = "fullscreen";
                }
                else
                {
                    _aspectRatio = "widescreen";
                }

                if (strFile.ToLower().EndsWith(".ifo") && driveInfo != null && driveInfo.IsOptical())
                {
                    // mediainfo is not able to obtain duration of IFO files
                    // so we use this to loop through all corresponding VOBs and add up the duration
                    // we do not do this for optical drives because there are issues with some discs
                    // taking more than 2 minutes(copy protection?)
                    _duration = 0;
                    string filePrefix = Path.GetFileName(strFile);
                    filePrefix = filePrefix.Substring(0, filePrefix.LastIndexOf('_'));
                    MediaInfo mi = new MediaInfo();
                    foreach (string file in Directory.GetFiles(Path.GetDirectoryName(strFile), filePrefix + "*.VOB"))
                    {
                        mi.Open(file);
                        int durationPart = 0;
                        int.TryParse(_mI.Get(StreamKind.Video, 0, "PlayTime"), out durationPart);
                        _duration += durationPart;
                    }
                }
                else
                {
                    int.TryParse(_mI.Get(StreamKind.Video, 0, "PlayTime"), out _duration);
                }

                _isInterlaced = (_scanType.IndexOf("interlaced") > -1);

                if (_height >= 720)
                {
                    _isHDTV = true;
                }
                else
                {
                    _isSDTV = true;
                }

                if ((_width == 1280 || _height == 720) && !_isInterlaced)
                {
                    _is720P = true;
                }

                if ((_width == 1920 || _height == 1080) && !_isInterlaced)
                {
                    _is1080P = true;
                }

                if ((_width == 1920 || _height == 1080) && _isInterlaced)
                {
                    _is1080I = true;
                }

                _isDIVX = (_videoCodec.IndexOf("dx50") > -1) | (_videoCodec.IndexOf("div3") > -1); // DivX 5 and DivX 3
                _isXVID = (_videoCodec.IndexOf("xvid") > -1);
                _isH264 = (_videoCodec.IndexOf("avc") > -1 || _videoCodec.IndexOf("h264") > -1);
                _isMP1V = (_videoCodec.IndexOf("mpeg-1v") > -1);
                _isMP2V = (_videoCodec.IndexOf("mpeg-2v") > -1);
                _isMP4V = (_videoCodec.IndexOf("fmp4") > -1); // add more
                _isWMV  = (_videoCodec.IndexOf("wmv") > -1);  // wmv3 = WMV9
                // missing cvid etc
                _isAC3    = (System.Text.RegularExpressions.Regex.IsMatch(_audioCodec, "ac-?3"));
                _isMP3    = (_audioCodec.IndexOf("mpeg-1 audio layer 3") > -1) || (_audioCodec.IndexOf("mpeg-2 audio layer 3") > -1);
                _isMP2A   = (_audioCodec.IndexOf("mpeg-1 audio layer 2") > -1);
                _isDTS    = (_audioCodec.IndexOf("dts") > -1);
                _isOGG    = (_audioCodec.IndexOf("ogg") > -1);
                _isAAC    = (_audioCodec.IndexOf("aac") > -1);
                _isWMA    = (_audioCodec.IndexOf("wma") > -1); // e.g. wma3
                _isPCM    = (_audioCodec.IndexOf("pcm") > -1);
                _isTrueHD = (_audioCodec.Contains("truehd") || _audioFormatProfile.Contains("truehd"));
                _isDTSHD  = (_audioCodec.Contains("dts") && (_audioFormatProfile.Contains("hra") || _audioFormatProfile.Contains("ma")));

                if (checkHasExternalSubtitles(strFile))
                {
                    _hasSubtitles = true;
                }
                else if (_numSubtitles > 0)
                {
                    _hasSubtitles = true;
                }
                else
                {
                    _hasSubtitles = false;
                }

                //logger.Debug("MediaInfoWrapper: inspecting media : {0}", strFile);
                //logger.Debug("MediaInfoWrapper: FrameRate : {0}", _framerate);
                //logger.Debug("MediaInfoWrapper: VideoCodec : {0}", _videoCodec);
                //if (_isDIVX)
                //  logger.Debug("MediaInfoWrapper: IsDIVX: {0}", _isDIVX);
                //if (_isXVID)
                //  logger.Debug("MediaInfoWrapper: IsXVID: {0}", _isXVID);
                //if (_isH264)
                //  logger.Debug("MediaInfoWrapper: IsH264: {0}", _isH264);
                //if (_isMP1V)
                //  logger.Debug("MediaInfoWrapper: IsMP1V: {0}", _isMP1V);
                //if (_isMP2V)
                //  logger.Debug("MediaInfoWrapper: IsMP2V: {0}", _isMP2V);
                //if (_isMP4V)
                //  logger.Debug("MediaInfoWrapper: IsMP4V: {0}", _isMP4V);
                //if (_isWMV)
                //  logger.Debug("MediaInfoWrapper: IsWMV: {0}", _isWMV);

                //logger.Debug("MediaInfoWrapper: HasSubtitles : {0}", _hasSubtitles);
                //logger.Debug("MediaInfoWrapper: NumSubtitles : {0}", _numSubtitles);
                //logger.Debug("MediaInfoWrapper: Scan type : {0}", _scanType);
                //logger.Debug("MediaInfoWrapper: IsInterlaced: {0}", _isInterlaced);
                //logger.Debug("MediaInfoWrapper: Width : {0}", _width);
                //logger.Debug("MediaInfoWrapper: Height : {0}", _height);
                //logger.Debug("MediaInfoWrapper: Audiochannels : {0}", _audioChannels);
                //logger.Debug("MediaInfoWrapper: Audiorate : {0}", _audioRate);
                //logger.Debug("MediaInfoWrapper: AspectRatio : {0}", _aspectRatio);
                //logger.Debug("MediaInfoWrapper: AudioCodec : {0}", _audioCodec);
                //if (_isAC3)
                //  logger.Debug("MediaInfoWrapper: IsAC3 : {0}", _isAC3);
                //if (_isMP3)
                //  logger.Debug("MediaInfoWrapper: IsMP3 : {0}", _isMP3);
                //if (_isMP2A)
                //  logger.Debug("MediaInfoWrapper: IsMP2A: {0}", _isMP2A);
                //if (_isDTS)
                //  logger.Debug("MediaInfoWrapper: IsDTS : {0}", _isDTS);
                //if (_isTrueHD)
                //  logger.Debug("MediaInfoWrapper: IsTrueHD : {0}", _isTrueHD);
                //if (_isDTSHD)
                //  logger.Debug("MediaInfoWrapper: IsDTSHD : {0}", _isDTSHD);
                //if (_isOGG)
                //  logger.Debug("MediaInfoWrapper: IsOGG : {0}", _isOGG);
                //if (_isAAC)
                //  logger.Debug("MediaInfoWrapper: IsAAC : {0}", _isAAC);
                //if (_isWMA)
                //  logger.Debug("MediaInfoWrapper: IsWMA: {0}", _isWMA);
                //if (_isPCM)
                //  logger.Debug("MediaInfoWrapper: IsPCM: {0}", _isPCM);
            }
            catch (Exception ex)
            {
                logger.Error("MediaInfo processing failed ('MediaInfo.dll' may be missing): {0}", ex.Message);
            }
            finally
            {
                if (_mI != null)
                {
                    _mI.Close();
                }
            }
        }
コード例 #55
0
 ///<summary>GeneralStream constructor.</summary>
 ///<param name="mediaInfo">A MediaInfo object.</param>
 ///<param name="id">The MediaInfo ID for this audio stream.</param>
 public GeneralStream(MediaInfo mediaInfo, int id)
     : base(mediaInfo, StreamKind.General, id)
 {
 }
コード例 #56
0
        static ReadOnlySpan <byte> IndexKeyword => new byte[] { 0x69, 0x6E, 0x64, 0x65, 0x78 };               // = index

        /// <summary>
        /// Parses FFprobe JSON output and returns a new <see cref="MediaInfo"/>
        /// </summary>
        /// <param name="data">JSON output</param>
        /// <param name="file">The file the JSON output format is about</param>
        /// <returns><see cref="MediaInfo"/> containing information from FFprobe output</returns>
        public static MediaInfo Read(byte[] data, string file)
        {
            var json = new Utf8JsonReader(data, isFinalBlock: false, state: default);


            var streams = new List <Dictionary <string, object> >();
            var format  = new Dictionary <string, object>();

            var currentStream = -1;

            var    currentObject = JsonObjects.None;
            string?lastKey       = null;

            while (json.Read())
            {
                JsonTokenType       tokenType = json.TokenType;
                ReadOnlySpan <byte> valueSpan = json.ValueSpan;
                switch (tokenType)
                {
                case JsonTokenType.StartObject:
                case JsonTokenType.EndObject:
                case JsonTokenType.Null:
                case JsonTokenType.StartArray:
                case JsonTokenType.EndArray:
                    break;

                case JsonTokenType.PropertyName:
                    if (valueSpan.SequenceEqual(StreamsKeyword))
                    {
                        currentObject = JsonObjects.Streams;
                        break;
                    }
                    if (valueSpan.SequenceEqual(FormatKeyword))
                    {
                        currentObject = JsonObjects.Format;
                        break;
                    }

                    if (valueSpan.SequenceEqual(IndexKeyword))
                    {
                        streams.Add(new Dictionary <string, object>());
                        currentStream++;
                    }

                    if (currentObject == JsonObjects.Streams)
                    {
                        lastKey = json.GetString();
                        if (lastKey != null)
                        {
                            streams[currentStream].TryAdd(lastKey, new object());
                        }
                    }
                    else if (currentObject == JsonObjects.Format)
                    {
                        lastKey = json.GetString();
                        if (lastKey != null)
                        {
                            format.TryAdd(lastKey, new object());
                        }
                    }
                    break;

                case JsonTokenType.String:
                    if (currentObject == JsonObjects.Streams && lastKey != null)
                    {
                        streams[currentStream][lastKey] = json.GetString() !;
                    }
                    else if (currentObject == JsonObjects.Format && lastKey != null)
                    {
                        format[lastKey] = json.GetString() !;
                    }
                    break;

                case JsonTokenType.Number:
                    if (!json.TryGetInt32(out int valueInteger))
                    {
#if DEBUG
                        System.Diagnostics.Trace.TraceWarning($"JSON number parse error: \"{lastKey}\" = {System.Text.Encoding.UTF8.GetString(valueSpan.ToArray())}, file = {file}");
#endif
                        break;
                    }

                    if (currentObject == JsonObjects.Streams && lastKey != null)
                    {
                        streams[currentStream][lastKey] = valueInteger;
                    }
                    else if (currentObject == JsonObjects.Format && lastKey != null)
                    {
                        format[lastKey] = valueInteger;
                    }
                    break;

                case JsonTokenType.True:
                case JsonTokenType.False:
                    bool valueBool = json.GetBoolean();
                    if (currentObject == JsonObjects.Streams && lastKey != null)
                    {
                        streams[currentStream][lastKey] = valueBool;
                    }
                    else if (currentObject == JsonObjects.Format && lastKey != null)
                    {
                        format[lastKey] = valueBool;
                    }
                    break;

                default:
                    throw new ArgumentException();
                }
            }

            var info = new MediaInfo {
                Streams = new MediaInfo.StreamInfo[streams.Count]
            };

            if (format.ContainsKey("duration") && TimeSpan.TryParse((string)format["duration"], out var duration))
            {
                /*
                 * Trim miliseconds here as we would have done it later anyway.
                 * Reasons are:
                 * - More user friendly
                 * - Allows an improved check against equality
                 * Cons are:
                 * - Not 100% accurate if you consider a difference of e.g. 2 miliseconds makes a duplicate no longer a duplicate
                 * - Breaking change at the moment of implementation as it doesn't apply to already scanned files
                 */
                info.Duration = duration.TrimMiliseconds();
            }

            var foundBitRate = false;
            for (int i = 0; i < streams.Count; i++)
            {
                info.Streams[i] = new MediaInfo.StreamInfo();
                if (streams[i].ContainsKey("bit_rate") && long.TryParse((string)streams[i]["bit_rate"], out var bitrate))
                {
                    foundBitRate            = true;
                    info.Streams[i].BitRate = bitrate;
                }
                if (streams[i].ContainsKey("width"))
                {
                    info.Streams[i].Width = (int)streams[i]["width"];
                }
                if (streams[i].ContainsKey("height"))
                {
                    info.Streams[i].Height = (int)streams[i]["height"];
                }
                if (streams[i].ContainsKey("codec_name"))
                {
                    info.Streams[i].CodecName = (string)streams[i]["codec_name"];
                }
                if (streams[i].ContainsKey("codec_long_name"))
                {
                    info.Streams[i].CodecLongName = (string)streams[i]["codec_long_name"];
                }
                if (streams[i].ContainsKey("codec_type"))
                {
                    info.Streams[i].CodecType = (string)streams[i]["codec_type"];
                }
                if (streams[i].ContainsKey("channel_layout"))
                {
                    info.Streams[i].ChannelLayout = (string)streams[i]["channel_layout"];
                }
                if (streams[i].ContainsKey("channels"))
                {
                    info.Streams[i].Channels = (int)streams[i]["channels"];
                }

                if (streams[i].ContainsKey("pix_fmt"))
                {
                    info.Streams[i].PixelFormat = (string)streams[i]["pix_fmt"];
                }
                if (streams[i].ContainsKey("sample_rate") && int.TryParse((string)streams[i]["sample_rate"], out var sample_rate))
                {
                    info.Streams[i].SampleRate = sample_rate;
                }
                if (streams[i].ContainsKey("index"))
                {
                    info.Streams[i].Index = ((int)streams[i]["index"]).ToString();
                }

                if (streams[i].ContainsKey("r_frame_rate"))
                {
                    var stringFrameRate = (string)streams[i]["r_frame_rate"];
                    if (stringFrameRate.Contains('/'))
                    {
                        var split = stringFrameRate.Split('/');
                        if (split.Length == 2 && int.TryParse(split[0], out var firstRate) && int.TryParse(split[1], out var secondRate))
                        {
                            info.Streams[i].FrameRate = (firstRate > 0 && secondRate > 0) ? firstRate / (float)secondRate : -1f;
                        }
                    }
                }
            }
            //Workaround if video stream bitrate is not set but in format
            if (!foundBitRate && info.Streams.Length > 0 && format.ContainsKey("bit_rate") && long.TryParse((string)format["bit_rate"], out var formatBitrate))
            {
                info.Streams[0].BitRate = formatBitrate;
            }

            return(info);
        }
コード例 #57
0
ファイル: OtherStream.cs プロジェクト: Mouaijin/DownloadSort
 ///<summary>OtherStream constructor.</summary>
 ///<param name="mediaInfo">A MediaInfo object.</param>
 ///<param name="id">The MediaInfo ID for this other stream.</param>
 public OtherStream(MediaInfo mediaInfo, int id)
     : base(mediaInfo, StreamKind.Other, id)
 {
 }
コード例 #58
0
        /// <summary>
        /// Metoda konwertuje plik z napisami do formatu MicroDVD
        /// {5222}{5271}Wiesz co bêdzie pierwsz¹ rzecz¹,|jak¹ zrobiê po powrocie do domu?
        /// {5272}{5292}Pozbêdziesz siê pryszczy?
        /// </summary>
        /// <param name="filePath">Œcie¿ka do pliku</param>
        public static void Convert(string filePath)
        {
            string newFileName = filePath;
            string oldFileName = filePath + ".old";

            string directory          = Path.GetDirectoryName(newFileName);
            string fileNameWithoutExt = Path.GetFileNameWithoutExtension(newFileName);
            string fileFilter         = fileNameWithoutExt + ".*";

            if (File.Exists(oldFileName))
            {
                File.Delete(oldFileName);
            }

            File.Move(newFileName, oldFileName);

            newFileName = fileNameWithoutExt + ".srt";

            string[] filePaths = Directory.GetFiles(directory, fileFilter);

            string videoFile = filePaths[0];


            MediaInfo MI = new MediaInfo();

            MI.Open(videoFile);
            string framRateString = MI.Get(StreamKind.Video, 0, "FrameRate");

            NumberFormatInfo provider = new NumberFormatInfo();

            provider.NumberDecimalSeparator = ".";
            provider.NumberGroupSeparator   = ",";
            double frameRate = 0;

            frameRate = (System.Convert.ToDouble(framRateString, provider));

            StreamReader reader = new StreamReader(oldFileName, Encoding.GetEncoding(1250));
            StreamWriter writer = new StreamWriter(newFileName, false, Encoding.GetEncoding(1250));

            String line;
            int    counter = 0;

            while ((line = reader.ReadLine()) != null)
            {
                counter++;
                int      start   = 0;
                int      stop    = 0;
                double   startD  = 0d;
                double   stopD   = 0d;
                string   startS  = "";
                string   stopS   = "";
                string   text    = "";
                TimeSpan startTS = new TimeSpan();
                TimeSpan stopTS  = new TimeSpan();



                if (line.StartsWith("["))
                { //MPL 2 [1000][1100]Tekst dialogu
                    string[] temp = line.Split(new string[] { "][" }, StringSplitOptions.RemoveEmptyEntries);

                    start = (int)(int.Parse(temp[0].Replace("[", "")));

                    int index = temp[1].IndexOf("]");
                    if (index > 0)
                    {
                        stop = (int)(int.Parse(temp[1].Substring(0, index)));
                        text = temp[1].Substring(index + 1).Replace("|", "\r\n");
                    }
                    else
                    {
                        stop = (int)(int.Parse(temp[1]));
                    }

                    startTS = new TimeSpan(0, 0, 0, (int)start / 10, start % 10 * 100);
                    stopTS  = new TimeSpan(0, 0, 0, (int)stop / 10, stop % 10 * 100);


                    if (temp.Length > 2)
                    {
                        for (int i = 2; i < temp.Length; i++)
                        {
                            text += temp[i].Replace("|", "\r\n");
                        }
                    }
                }
                else if (Regex.IsMatch(line.Substring(0, 1), @"\d"))
                { //TMP 00:10:15:Tekst dialogu
                    string[] temp = line.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);

                    int h = int.Parse(temp[0]);
                    int m = int.Parse(temp[1]);
                    int s = int.Parse(temp[2]);

                    startTS = new TimeSpan(0, h, m, s, 0);

                    //Gdy dialog jest d³u¿szy wyœwietlamy napisy przez 4 sekundy
                    if (line.Length > 40)
                    {
                        stopTS = startTS.Add(new TimeSpan(0, 0, 4));
                    }
                    else
                    {
                        stopTS = startTS.Add(new TimeSpan(0, 0, 2));
                    }

                    if (temp.Length > 3)
                    {
                        for (int i = 3; i < temp.Length; i++)
                        {
                            text += temp[i].Replace("|", "\r\n");
                        }
                        ;
                    }
                }
                else if (line.StartsWith("{"))
                { //MicroDVD {1000}{1100}Tekst dialogu
                    string[] temp = line.Split(new string[] { "}{" }, StringSplitOptions.RemoveEmptyEntries);

                    startD = (double.Parse(temp[0].Replace("{", ""))) / frameRate;

                    int index = temp[1].IndexOf("}");
                    if (index > 0)
                    {
                        stopD = (double.Parse(temp[1].Substring(0, index))) / frameRate;
                        text  = temp[1].Substring(index + 1).Replace("|", "\r\n");
                    }
                    else
                    {
                        stopD = (double.Parse(temp[1])) / frameRate;
                    }

                    startTS = new TimeSpan(0, 0, 0, 0, (int)(startD * 1000d));
                    stopTS  = new TimeSpan(0, 0, 0, 0, (int)(stopD * 1000d));

                    if (temp.Length > 2)
                    {
                        for (int i = 2; i < temp.Length; i++)
                        {
                            text += temp[i].Replace("|", "\r\n");
                        }
                    }
                }

                //Formatowanie czasu
                startS = string.Format("{0:00}:{1:00}:{2:00},{3:000}", startTS.Hours, startTS.Minutes, startTS.Seconds, startTS.Milliseconds);
                stopS  = string.Format("{0:00}:{1:00}:{2:00},{3:000}", stopTS.Hours, stopTS.Minutes, stopTS.Seconds, stopTS.Milliseconds);

                //I zapis wiersza do pliku
                writer.WriteLine(counter.ToString());
                writer.WriteLine(startS + " --> " + stopS);
                writer.WriteLine(text);
                writer.WriteLine();
            }
            reader.Close();
            writer.Close();
        }
コード例 #59
0
 public MediaInfoGrabber(string pathToToolkit, string probeResultsFolderPath, string fileName)
 {
     Info = new MediaInfo(fileName);
     PathToToolkit = pathToToolkit;
     ProbeResultsFolderPath = probeResultsFolderPath;
 }
コード例 #60
0
ファイル: mp.cs プロジェクト: XAOS-Interactive/mpv.net
        static void ReadMetaData()
        {
            lock (MediaTracks)
            {
                MediaTracks.Clear();
                string path = get_property_string("path");

                if (File.Exists(path))
                {
                    using (MediaInfo mi = new MediaInfo(path))
                    {
                        int count = mi.GetCount(MediaInfoStreamKind.Video);

                        for (int i = 0; i < count; i++)
                        {
                            MediaTrack track = new MediaTrack();
                            Add(track, mi.GetVideo(i, "Format"));
                            Add(track, mi.GetVideo(i, "Format_Profile"));
                            Add(track, mi.GetVideo(i, "Width") + "x" + mi.GetVideo(i, "Height"));
                            Add(track, mi.GetVideo(i, "FrameRate") + " FPS");
                            Add(track, mi.GetVideo(i, "Language/String"));
                            Add(track, mi.GetVideo(i, "Forced") == "Yes" ? "Forced" : "");
                            Add(track, mi.GetVideo(i, "Default") == "Yes" ? "Default" : "");
                            Add(track, mi.GetVideo(i, "Title"));
                            track.Text = "V: " + track.Text.Trim(' ', ',');
                            track.Type = "v";
                            track.ID   = i + 1;
                            MediaTracks.Add(track);
                        }

                        count = mi.GetCount(MediaInfoStreamKind.Audio);

                        for (int i = 0; i < count; i++)
                        {
                            MediaTrack track = new MediaTrack();
                            Add(track, mi.GetAudio(i, "Language/String"));
                            Add(track, mi.GetAudio(i, "Format"));
                            Add(track, mi.GetAudio(i, "Format_Profile"));
                            Add(track, mi.GetAudio(i, "BitRate/String"));
                            Add(track, mi.GetAudio(i, "Channel(s)/String"));
                            Add(track, mi.GetAudio(i, "SamplingRate/String"));
                            Add(track, mi.GetAudio(i, "Forced") == "Yes" ? "Forced" : "");
                            Add(track, mi.GetAudio(i, "Default") == "Yes" ? "Default" : "");
                            Add(track, mi.GetAudio(i, "Title"));
                            track.Text = "A: " + track.Text.Trim(' ', ',');
                            track.Type = "a";
                            track.ID   = i + 1;
                            MediaTracks.Add(track);
                        }

                        count = mi.GetCount(MediaInfoStreamKind.Text);

                        for (int i = 0; i < count; i++)
                        {
                            MediaTrack track = new MediaTrack();
                            Add(track, mi.GetText(i, "Language/String"));
                            Add(track, mi.GetText(i, "Format"));
                            Add(track, mi.GetText(i, "Format_Profile"));
                            Add(track, mi.GetText(i, "Forced") == "Yes" ? "Forced" : "");
                            Add(track, mi.GetText(i, "Default") == "Yes" ? "Default" : "");
                            Add(track, mi.GetText(i, "Title"));
                            track.Text = "S: " + track.Text.Trim(' ', ',');
                            track.Type = "s";
                            track.ID   = i + 1;
                            MediaTracks.Add(track);
                        }

                        count = get_property_int("edition-list/count");

                        for (int i = 0; i < count; i++)
                        {
                            MediaTrack track = new MediaTrack();
                            track.Text = "E: " + get_property_string($"edition-list/{i}/title");
                            track.Type = "e";
                            track.ID   = i;
                            MediaTracks.Add(track);
                        }

                        void Add(MediaTrack track, string val)
                        {
                            if (!string.IsNullOrEmpty(val) && !(track.Text != null && track.Text.Contains(val)))
                            {
                                track.Text += " " + val + ",";
                            }
                        }
                    }
                }
            }

            lock (Chapters)
            {
                Chapters.Clear();
                int count = get_property_int("chapter-list/count");

                for (int x = 0; x < count; x++)
                {
                    string text = get_property_string($"chapter-list/{x}/title");
                    double time = get_property_number($"chapter-list/{x}/time");
                    Chapters.Add(new KeyValuePair <string, double>(text, time));
                }
            }
        }