/// <summary>
        /// Transcode video to a mp4 file
        /// </summary>
        /// <param name="inputPath">File path to source</param>
        /// <param name="profile">Preset profile to transcode to</param>
        /// <param name="videoType">Video type (tv or movie)</param>
        public void Transcode(string inputPath, string profile, VideoType videoType)
        {
            //strip the file name out
            var filename = DirectoryHelpers.ExtractFilename(inputPath);

            var startInfo = new ProcessStartInfo();
            startInfo.FileName = HandbrakePath;
            startInfo.Arguments = string.Format("-i \"{0}\"", inputPath);
            if (videoType == VideoType.Movie)
            {
                startInfo.Arguments += string.Format(" -o \"{0}movies\\{1} ({2}).mp4\"", _outputPath, filename, profile);
            }
            if (videoType == VideoType.TvShowEpisode)
            {
                startInfo.Arguments += string.Format(" -o \"{0}shows\\{1} ({2}).mp4\"", _outputPath, filename, profile);
            }
            startInfo.Arguments += string.Format(" --preset=\"{0}\"", profile);

            startInfo.CreateNoWindow = false;
            startInfo.UseShellExecute = false;
            using(var process = Process.Start(startInfo))
            {
                process.WaitForExit();
            }
        }
 /// <summary>
 /// 初始化环境
 /// </summary>
 /// <param name="hdlwin">初始化当前窗口</param>
 /// <param name="videotype">视频卡类别</param>
 /// <returns>返回视频卡通道数量</returns>
 public int InitVideo(IntPtr hdlwin, VideoType videotype)
 {
     int channel = 0;
     switch (videotype)
     {
         case VideoType.MvAPI:
             try
             {
                 channel = (int)MvAPI.MV_GetDeviceNumber();
             }
             catch (Exception ex)
             {
                 channel = 0;
             }
             break;
         case VideoType.Sa7134Capture:
             try
             {
                 if (Sa7134Capture.VCAInitSdk(hdlwin, DISPLAYTRANSTYPE.PCI_MEMORY_VIDEOMEMORY, false))
                     channel = Sa7134Capture.VCAGetDevNum();
             }
             catch (Exception ex)
             {
                 channel = 0;
             }
             break;
     }
     if (channel > 0)
     {
         this.channelHandle.Clear();
         this.VideoType = videotype;
     }
     return channel;
 }
        private void handleVideoToggleButtonClick(System.Windows.Controls.Primitives.ToggleButton button, ref VideoWindow window, VideoType videoType)
        {
            if (button.IsChecked.GetValueOrDefault(false))
            {
                if (window != null)
                {
                    window.Close();
                }

                window = new VideoWindow();
                window.SetSensorVideo(nuiSensor, videoType);
                window.Closed += delegate(object cSender, EventArgs cArgs)
                {
                    button.IsChecked = false;
                };
                window.Show();
            }
            else
            {
                if (window != null)
                {
                    window.Close();
                    window = null;
                }
            }
        }
        /// <summary>
        /// Gets the type of the input.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="isoType">Type of the iso.</param>
        /// <returns>InputType.</returns>
        public static InputType GetInputType(string path, VideoType? videoType, IsoType? isoType)
        {
            var type = InputType.AudioFile;

            if (videoType.HasValue)
            {
                switch (videoType.Value)
                {
                    case VideoType.BluRay:
                        type = InputType.Bluray;
                        break;
                    case VideoType.Dvd:
                        type = InputType.Dvd;
                        break;
                    case VideoType.Iso:
                        if (isoType.HasValue)
                        {
                            switch (isoType.Value)
                            {
                                case IsoType.BluRay:
                                    type = InputType.Bluray;
                                    break;
                                case IsoType.Dvd:
                                    type = InputType.Dvd;
                                    break;
                            }
                        }
                        break;
                }
            }

            return type;
        }
Beispiel #5
0
        public static List<NavLibrary> LoadLibraries(string username, VideoType videoType)
        {
            var cacheKey = username + (videoType == VideoType.Movie ? "MovieLibraries" : "ShowsLibraries");
            var names = new List<NavLibrary>();

            var cnames = (List<NavLibrary>)HttpContext.Current.Cache[cacheKey];

            if (cnames == null)
            {
                using (var db = new MediaManagerDataContext())
                {
                    var user = db.Users.FirstOrDefault(a => a.UserName == username);

                    if (user != null)
                    {
                        var libraries = user.UserXServers.Select(a => a.Server).SelectMany(a => a.Libraries);

                        names = videoType == VideoType.Movie ?
                            libraries.Where(a => a.ServerMedias.Any(b => b.Movie != null)).Select(a => new NavLibrary() {Name = a.Name, ServerName = a.Server.Name, ServerId = a.ServerId}).ToList()
                            : libraries.Where(a => a.ServerMedias.Any(b => b.Episode != null)).Select(a => new NavLibrary() {Name = a.Name, ServerName = a.Server.Name, ServerId = a.ServerId}).ToList();

                        // cache the value with a 15 minute sliding, and 1 day abolute expiration
                        HttpContext.Current.Cache.Add(cacheKey, names, null, DateTime.MaxValue, new TimeSpan(0, 0, 15, 0), CacheItemPriority.Normal, null);
                    }
                }
            }
            else
            {
                names = cnames;
            }

            return names;
        }
        public void SetSensorVideo(NuiSensor sensor, VideoType videoType)
        {
            this.videoType = videoType;
            this.sensor = sensor;

            Title = videoType.ToString();

            sensor.HandTracker.HandDestroy += new EventHandler<HandDestroyEventArgs>(HandTracker_HandDestroy);
            sensor.HandTracker.HandUpdate += new EventHandler<HandUpdateEventArgs>(HandTracker_HandUpdate);

            refreshWorker = new BackgroundWorker();
            refreshWorker.DoWork += new DoWorkEventHandler(refreshWorker_DoWork);
            CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);

            //create finger points
            for (int i = 0; i < MultiTouchTracker.MAX_FINGERS; i++)
            {
                Ellipse ellipse = new Ellipse()
                {
                    Width = 10,
                    Height = 10,
                    Fill = Brushes.Orange,
                    Stroke = Brushes.White,
                    StrokeThickness = 2,
                    Opacity = 0,
                };
                fingerPoints.Add(ellipse);
                canvas.Children.Add(ellipse);
            }
        }
        public void EnumHelper_Parse_ReturnsCorrectEnum(string value, VideoType videoType)
        {
            //act
            var result = EnumHelper<VideoType>.Parse(value);

            //assert
            result.Should().Be(videoType);
        }
 	/// <summary>
 	/// Represents a video through a set of locally held attributes.
 	/// </summary>
 	/// <param name="location">
 	/// The "location" of the video on the internet. In other words, the string representation of the url for the video.
 	/// </param>
 	/// <param name="res">
 	/// The resolution of the video.
 	/// </param>
 	/// <param name="format">
 	/// The format (or extension) of the video.
 	/// </param>
 	public Video(string location, int res, VideoType format)
 	{
 		
 		this.Location = location;
 		this.Resolution = res;
 		this.Format = format;
 		
 	}
Beispiel #9
0
 private VideoInfo(string title, VideoType type, int year, int season, int episode)
 {
     Title = title;
     Type = type;
     Year = year;
     Season = season;
     Episode = episode;
 }
Beispiel #10
0
 private VideoInfo(int formatCode, VideoType videoType, int resolution, bool is3D, AudioType audioType, int audioBitrate)
 {
     this.FormatCode = formatCode;
     this.VideoType = videoType;
     this.Resolution = resolution;
     this.Is3D = is3D;
     this.AudioType = audioType;
     this.AudioBitrate = audioBitrate;
 }
 private VideoInfo(int formatCode, VideoType videoType, int resolution, bool is3D, AudioType audioType, int audioBitrate)
 {
     FormatCode = formatCode;
     VideoType = videoType;
     Resolution = resolution;
     Is3D = is3D;
     AudioType = audioType;
     AudioBitrate = audioBitrate;
 }
 public void Verify_Add_Should_AddTheEntityToTheContext()
 {
     // Arrange
     Mock<IDbSet<VideoType>> mockSetVideoTypes;
     var mockContext = VideoTypesMockingSetup.DoMockingSetupForContext(false, out mockSetVideoTypes);
     var repository = new VideoTypesRepository(mockContext.Object);
     var videoTypes = new VideoType { Active = true, CustomKey = "SALVATORE-RAA", };
     // Act
     repository.Add(videoTypes);
     // Assert
     mockSetVideoTypes.Verify(x => x.Add(videoTypes), Times.Once);
 }
 /// <summary>
 ///     Downloads context to audio, requires Url, Optional - VideoInfo (Default: Highest Quality), Optional - BaseDirectory
 /// </summary>
 public async static Task ToVideoAsync(this YoutubeContext context, VideoType customtype = VideoType.Mp4) {
     if (context==null)
         throw new ArgumentException(nameof(context));
     if (string.IsNullOrEmpty(context.Url))
         throw new ArgumentException(nameof(context.Url));
     
     if (context.VideoInfo == null)
         await context.FindHighestVideoQualityDownloadUrlAsync(customtype);
     
     var vd = new VideoDownloader(context);
     await vd.ExecuteAsync();
 }
 /// <summary>
 ///     Downloads context to audio, requires Url, Optional - VideoInfo (Default: Highest Quality), Optional - BaseDirectory
 /// </summary>
 public static void ToVideo(this YoutubeContext context, VideoType customtype = VideoType.Mp4) {
     if (context==null)
         throw new ArgumentException(nameof(context));
     if (string.IsNullOrEmpty(context.Url))
         throw new ArgumentException(nameof(context.Url));
     
     if (context.VideoInfo == null)
         DownloadUrlResolver.FindHighestVideoQualityDownloadUrl(context, customtype);
     
     var vd = new VideoDownloader(context);
     vd.Execute();
 }
Beispiel #15
0
 public static void SimpleDownloadVideo(string video_url, string title, string folder_destination, VideoType format, Form1 form)
 {
     IEnumerable<VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(video_url);
     VideoInfo video = videoInfos.First(info => info.VideoType == format);
     if (video.RequiresDecryption)
     {
         DownloadUrlResolver.DecryptDownloadUrl(video);
     }
     var videoDownloader = new VideoDownloader(video, Path.Combine(folder_destination, title + video.VideoExtension));
     videoDownloader.DownloadProgressChanged += (sender, args2) => form.SetProgressBarValue(Convert.ToInt32(args2.ProgressPercentage));
     videoDownloader.Execute();
 }
        /// <summary>
        /// Gets the input argument.
        /// </summary>
        /// <param name="videoPath">The video path.</param>
        /// <param name="isRemote">if set to <c>true</c> [is remote].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="isoType">Type of the iso.</param>
        /// <param name="isoMount">The iso mount.</param>
        /// <param name="playableStreamFileNames">The playable stream file names.</param>
        /// <param name="type">The type.</param>
        /// <returns>System.String[][].</returns>
        public static string[] GetInputArgument(string videoPath, bool isRemote, VideoType videoType, IsoType? isoType, IIsoMount isoMount, IEnumerable<string> playableStreamFileNames, out InputType type)
        {
            var inputPath = isoMount == null ? new[] { videoPath } : new[] { isoMount.MountedPath };

            type = InputType.File;

            switch (videoType)
            {
                case VideoType.BluRay:
                    type = InputType.Bluray;
                    inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray();
                    break;
                case VideoType.Dvd:
                    type = InputType.Dvd;
                    inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray();
                    break;
                case VideoType.Iso:
                    if (isoType.HasValue)
                    {
                        switch (isoType.Value)
                        {
                            case IsoType.BluRay:
                                type = InputType.Bluray;
                                inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray();
                                break;
                            case IsoType.Dvd:
                                type = InputType.Dvd;
                                inputPath = GetPlayableStreamFiles(inputPath[0], playableStreamFileNames).ToArray();
                                break;
                        }
                    }
                    break;
                case VideoType.VideoFile:
                    {
                        if (isRemote)
                        {
                            type = InputType.Url;
                        }
                        break;
                    }
            }

            return inputPath;
        }
        /// <summary>
        /// Gets the probe size argument.
        /// </summary>
        /// <param name="mediaPath">The media path.</param>
        /// <param name="isVideo">if set to <c>true</c> [is video].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="isoType">Type of the iso.</param>
        /// <returns>System.String.</returns>
        protected string GetProbeSizeArgument(string mediaPath, bool isVideo, VideoType? videoType, IsoType? isoType)
        {
            var type = !isVideo ? MediaEncoderHelpers.GetInputType(mediaPath, null, null) :
                MediaEncoderHelpers.GetInputType(mediaPath, videoType, isoType);

            return MediaEncoder.GetProbeSizeArgument(type);
        }
 public void AddFreeFirstAidVideo(VideoType videoType)
 {
     Console.WriteLine(Constants.VideoFirstAidFree);
 }
Beispiel #19
0
 public PlaylistItem(string title, string author, ImageSource thumbnailPath, string videoPath, VideoType videoType)
 {
     Title         = title;
     Author        = author;
     ThumbnailPath = thumbnailPath;
     VideoPath     = videoPath;
     VideoType     = videoType;
 }
Beispiel #20
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);
            }

            return(info);
        }
Beispiel #21
0
        private static void ParseYouTubeInfoType(string startType, string decoded, bool[] CheckingData, ObservableCollection <VideoInformation> AllInfo, string url, out VideoType type, out string codes, string fallbackhost, string signature, VideoQuality quality)
        {
            //Debug.WriteLine(decoded);

            string[] t2  = decoded.Substring(5, decoded.Length - 5).Split(';');
            string   tt2 = t2[0];

            if (t2.Length > 1)
            {
                codes = t2[1];
                codes = codes.Substring(0, codes.Length - 1);
                codes = codes.Substring(9, codes.Length - 9);
            }
            else
            {
                codes = ""; // Mostly for FLV video
            }
            tt2 = tt2.Replace('/', '_').Replace('-', '_');

            try
            {
                type = (VideoType)Enum.Parse(typeof(VideoType), tt2); // type=video/webm;+codecs="vp8.0,+vorbis"
            }
            catch (Exception eee)
            {
                type = VideoType.NULL;
                Debug.WriteLine("Unknown video type: " + tt2);
            }

            if (AllInfo.Count > 0)
            {
                foreach (VideoInformation info in AllInfo)
                {
                    if (info.Type == VideoType.NULL)
                    {
                        info.Codes = codes;
                        info.Type  = type;
                        return;
                    }
                }
            }
            AllInfo.Add(new VideoInformation(null, type, codes, null, null, VideoQuality.NULL));

            //        CheckAndAddWhenFull(startType, decoded, CheckingData, 1, AllInfo, url, type, codes, fallbackhost, signature, quality);
        }
        public MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType videoType, bool isAudio, string path, MediaProtocol protocol)
        {
            var info = new Model.MediaInfo.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;
                    }
                }
            }

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

                var tags = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

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

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

                    if (audioStream != null && audioStream.tags != null)
                    {
                        foreach (var pair in audioStream.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;
                    }
                }

                SetAudioInfoFromTags(info, tags);
            }
            else
            {
                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);
            }

            return info;
        }
Beispiel #23
0
        /// <summary>
        /// Convert a video do a different format.
        /// </summary>
        /// <param name="source">Input video source.</param>
        /// <param name="output">Output information.</param>
        /// <param name="type">Target conversion video type.</param>
        /// <param name="speed">Conversion target speed/quality (faster speed = lower quality).</param>
        /// <param name="size">Video size.</param>
        /// <param name="audioQuality">Conversion target audio quality.</param>
        /// <param name="multithreaded">Is encoding multithreaded.</param>
        /// <returns>Output video information.</returns>
        public VideoInfo Convert(
            VideoInfo source,
            FileInfo output,
            VideoType type = VideoType.Mp4,
            Speed speed    =
            Speed.SuperFast,
            VideoSize size =
            VideoSize.Original,
            AudioQuality audioQuality = AudioQuality.Normal,
            bool multithreaded        = false)
        {
            FFMpegHelper.ConversionExceptionCheck(source.ToFileInfo(), output);
            FFMpegHelper.ExtensionExceptionCheck(output, FileExtension.ForType(type));
            FFMpegHelper.ConversionSizeExceptionCheck(source);

            string args = "";

            var scale = VideoSize.Original == size ? 1 :
                        (double)source.Height / (int)size;

            var outputSize = new Size(
                (int)(source.Width / scale),
                (int)(source.Height / scale)
                );

            if (outputSize.Width % 2 != 0)
            {
                outputSize.Width += 1;
            }

            switch (type)
            {
            case VideoType.Mp4:
                args = Arguments.Input(source) +
                       Arguments.Threads(multithreaded) +
                       Arguments.Scale(outputSize) +
                       Arguments.Video(VideoCodec.LibX264, 2400) +
                       Arguments.Speed(speed) +
                       Arguments.Audio(AudioCodec.Aac, audioQuality) +
                       Arguments.Output(output);
                break;

            case VideoType.Ogv:
                args = Arguments.Input(source) +
                       Arguments.Threads(multithreaded) +
                       Arguments.Scale(outputSize) +
                       Arguments.Video(VideoCodec.LibTheora, 2400) +
                       Arguments.Speed(16) +
                       Arguments.Audio(AudioCodec.LibVorbis, audioQuality) +
                       Arguments.Output(output);
                break;

            case VideoType.Ts:
                args = Arguments.Input(source) +
                       Arguments.Copy() +
                       Arguments.BitStreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB) +
                       Arguments.ForceFormat(VideoCodec.MpegTs) +
                       Arguments.Output(output);
                break;
            }

            if (!RunProcess(args, output))
            {
                throw new FFMpegException(FFMpegExceptionType.Conversion, $"The video could not be converted to {Enum.GetName(typeof(VideoType), type)}");
            }

            return(new VideoInfo(output));
        }
Beispiel #24
0
            public async Task <Models.Helix.Videos.GetVideos.GetVideosResponse> GetVideoAsync(List <string> videoIds = null, string userId = null, string gameId = null, string after = null, string before = null, int first = 20, string language = null, Period period = Period.All, VideoSort sort = VideoSort.Time, VideoType type = VideoType.All)
            {
                if ((videoIds == null || videoIds.Count == 0) && userId == null && gameId == null)
                {
                    throw new BadParameterException("VideoIds, userId, and gameId cannot all be null/empty.");
                }
                if (videoIds != null && videoIds.Count > 0 && userId != null ||
                    videoIds != null && videoIds.Count > 0 && gameId != null ||
                    userId != null && gameId != null)
                {
                    throw new BadParameterException("If videoIds are present, you may not use userid or gameid. If gameid is present, you may not use videoIds or userid. If userid is present, you may not use videoids or gameids.");
                }

                var getParams = new List <KeyValuePair <string, string> >();

                if (videoIds != null && videoIds.Count > 0)
                {
                    foreach (var videoId in videoIds)
                    {
                        getParams.Add(new KeyValuePair <string, string>("id", videoId));
                    }
                }
                if (userId != null)
                {
                    getParams.Add(new KeyValuePair <string, string>("user_id", userId));
                }
                if (gameId != null)
                {
                    getParams.Add(new KeyValuePair <string, string>("game_id", gameId));
                }

                if (userId != null || gameId != null)
                {
                    if (after != null)
                    {
                        getParams.Add(new KeyValuePair <string, string>("after", after));
                    }
                    if (before != null)
                    {
                        getParams.Add(new KeyValuePair <string, string>("before", before));
                    }
                    getParams.Add(new KeyValuePair <string, string>("first", first.ToString()));
                    if (language != null)
                    {
                        getParams.Add(new KeyValuePair <string, string>("language", language));
                    }
                    switch (period)
                    {
                    case Period.All:
                        getParams.Add(new KeyValuePair <string, string>("period", "all"));
                        break;

                    case Period.Day:
                        getParams.Add(new KeyValuePair <string, string>("period", "day"));
                        break;

                    case Period.Month:
                        getParams.Add(new KeyValuePair <string, string>("period", "month"));
                        break;

                    case Period.Week:
                        getParams.Add(new KeyValuePair <string, string>("period", "week"));
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(period), period, null);
                    }
                    switch (sort)
                    {
                    case VideoSort.Time:
                        getParams.Add(new KeyValuePair <string, string>("sort", "time"));
                        break;

                    case VideoSort.Trending:
                        getParams.Add(new KeyValuePair <string, string>("sort", "trending"));
                        break;

                    case VideoSort.Views:
                        getParams.Add(new KeyValuePair <string, string>("sort", "views"));
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(sort), sort, null);
                    }
                    switch (type)
                    {
                    case VideoType.All:
                        getParams.Add(new KeyValuePair <string, string>("type", "all"));
                        break;

                    case VideoType.Highlight:
                        getParams.Add(new KeyValuePair <string, string>("type", "highlight"));
                        break;

                    case VideoType.Archive:
                        getParams.Add(new KeyValuePair <string, string>("type", "archive"));
                        break;

                    case VideoType.Upload:
                        getParams.Add(new KeyValuePair <string, string>("type", "upload"));
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(type), type, null);
                    }
                }

                return(await Api.GetGenericAsync <Models.Helix.Videos.GetVideos.GetVideosResponse>("https://api.twitch.tv/helix/videos", getParams, null, ApiVersion.Helix).ConfigureAwait(false));
            }
Beispiel #25
0
 public IosRecordScreenOptions(VideoType videoType, VideoQuality videoQuality)
 {
     VideoQuality = videoQuality.ToString().ToLower();
     VideoType    = videoType.ToString().ToLower();
 }
Beispiel #26
0
 public IosRecordScreenOptions(VideoType videoThing)
 {
     VideoType = videoThing.ToString().ToLower();
 }
Beispiel #27
0
        private static void ParseYouTubeInfo_Quality(string startType, string decoded, bool[] CheckingData, ObservableCollection <VideoInformation> AllInfo, string url, VideoType type, string codes, string fallbackhost, string signature, out VideoQuality quality)
        {
            //Debug.WriteLine(decoded);
            int    EqualIndex = decoded.IndexOf('=') + 1;
            string q2         = decoded.Substring(EqualIndex, decoded.Length - EqualIndex).Split(',')[0]; // hd1080,itag=37

            q2 = q2.Replace('/', '_').Replace('-', '_');

            try
            {
                quality = (VideoQuality)Enum.Parse(typeof(VideoQuality), q2);
            }
            catch (Exception eee)
            {
                switch (q2)
                {
                case "1920x1080":
                    quality = VideoQuality.hd1080;
                    break;

                case "1280x720":
                    quality = VideoQuality.hd720;
                    break;

                case "854x480":
                case "640x480":
                    quality = VideoQuality.large;
                    break;

                case "640x360":
                case "480x360":
                    quality = VideoQuality.medium;
                    break;

                case "320x240":
                case "426x240":
                case "256x144":
                case "192x144":
                    quality = VideoQuality.small;
                    break;

                default:
                    quality = VideoQuality.NULL;
                    Debug.WriteLine("Unknown quality: " + q2);
                    break;
                }
            }

            // Quality is the last.
            // quality isn't the last anymore, after the recent youtube changes

            if (AllInfo.Count > 0)
            {
                foreach (VideoInformation info in AllInfo)
                {
                    if (info.Quality == VideoQuality.NULL)
                    {
                        info.Quality = quality;
                        return;
                    }
                }
            }
            AllInfo.Add(new VideoInformation(null, VideoType.NULL, null, null, null, quality));

            //         CheckAndAddWhenFull(startType, decoded, CheckingData, 4, AllInfo, url, type, codes, fallbackhost, signature, quality);
        }
Beispiel #28
0
        /// <summary>
        /// https://github.com/rg3/youtube-dl/blob/master/youtube_dl/extractor/youtube.py
        /// </summary>
        /// <param name="startType"></param>
        /// <param name="decoded"></param>
        /// <param name="CheckingData"></param>
        /// <param name="AllInfo"></param>
        /// <param name="url"></param>
        /// <param name="type"></param>
        /// <param name="codes"></param>
        /// <param name="fallbackhost"></param>
        /// <param name="signature"></param>
        /// <param name="quality"></param>
        private static void ParseYouTubeInfo_Signature(string startType, string decoded, bool[] CheckingData, ObservableCollection <VideoInformation> AllInfo, string url, VideoType type, string codes, string fallbackhost, out string signature, VideoQuality quality)
        {
            //Debug.WriteLine(decoded);

            if (decoded.StartsWith("signature="))
            {
                signature = decoded.Substring(10, decoded.Length - 10);
            }
            if (decoded.StartsWith("sig="))
            {
                signature = decoded.Substring(4, decoded.Length - 4);
            }
            else if (decoded.StartsWith("s="))
            {
                signature = decoded.Substring(2, decoded.Length - 2);
            }
            else
            {
                int IndexOfEqual = decoded.IndexOf('=');
                signature = decoded.Substring(IndexOfEqual + 1, decoded.Length - (IndexOfEqual + 1));
            }
            if (JavascriptEngine != null)
            {
                JsValue retValue = JavascriptEngine.Invoke(DecodeFuncName, signature);

                signature = retValue.AsString();
            }
            else
            {
                signature = new DecryptSignature(signature).decrypt();
            }

            /*    if (SignatureDecodeArray.Count == 0)
             *  {
             *      SignatureDecodeArray.Add(92, new short[] { -2, 0, -3, 9, -3, 43, -3, 0, 23 });
             *      SignatureDecodeArray.Add(88, new short[] { -2, 1, 10, 0, -2, 23, -3, 15, 34 });
             *      SignatureDecodeArray.Add(87, new short[] { -3, 0, 63, -2, 0, -1 });
             *      SignatureDecodeArray.Add(85, new short[] { 0, -2, 17, 61, 0, -1, 7, -1 });
             *      SignatureDecodeArray.Add(83, new short[] { 24, 53, -2, 31, 4 });
             *      SignatureDecodeArray.Add(81, new short[] { 34, 29, 9, 0, 39, 24 });
             *  }
             *  if (SignatureDecodeArray.ContainsKey(signature.Length))
             *  {
             *      signature = ParseYouTubeEncoding(signature, SignatureDecodeArray[signature.Length]);
             *  }*/

            if (AllInfo.Count > 0)
            {
                foreach (VideoInformation info in AllInfo)
                {
                    if (info.Signature == null)
                    {
                        info.Signature = signature;
                        return;
                    }
                }
            }
            AllInfo.Add(new VideoInformation(null, VideoType.NULL, null, null, signature, VideoQuality.NULL));

            //         CheckAndAddWhenFull(startType, decoded, CheckingData, 3, AllInfo, url, type, codes, fallbackhost, signature, quality);
        }
Beispiel #29
0
        private static void ParseYouTubeInfo_FallBackHost(string startType, string decoded, bool[] CheckingData, ObservableCollection <VideoInformation> AllInfo, string url, VideoType type, string codes, out string fallbackhost, string signature, VideoQuality quality)
        {
            //Debug.WriteLine(decoded);

            fallbackhost = decoded.Substring(14, decoded.Length - 14); // fallback_host=tc.v19.cache8.c.youtube.com

            if (AllInfo.Count > 0)
            {
                foreach (VideoInformation info in AllInfo)
                {
                    if (info.FallbackHost == null)
                    {
                        info.FallbackHost = fallbackhost;
                        return;
                    }
                }
            }
            AllInfo.Add(new VideoInformation(null, VideoType.NULL, null, fallbackhost, null, VideoQuality.NULL));

            //        CheckAndAddWhenFull(startType, decoded, CheckingData, 2, AllInfo, url, type, codes, fallbackhost, signature, quality);
        }
Beispiel #30
0
 public InternalItemsQuery()
 {
     Tags = new string[] { };
     OfficialRatings = new string[] { };
     SortBy = new string[] { };
     MediaTypes = new string[] { };
     IncludeItemTypes = new string[] { };
     ExcludeItemTypes = new string[] { };
     Genres = new string[] { };
     Studios = new string[] { };
     StudioIds = new string[] { };
     ImageTypes = new ImageType[] { };
     VideoTypes = new VideoType[] { };
     Years = new int[] { };
     PersonTypes = new string[] { };
     PersonIds = new string[] { };
     ChannelIds = new string[] { };
     ItemIds = new string[] { };
 }
 /// <summary>
 /// Represents a video through a set of locally held attributes.
 /// </summary>
 /// <param name="pos">
 /// The position of the Video within the current list.
 /// </param>
 /// <param name="location">
 /// The "location" of the video on the internet. In other words, the string representation of the url for the video.
 /// </param>
 /// <param name="quality">
 /// The consumption quality of the video.
 /// </param>
 /// <param name="format">
 /// The format (or extension) of the video.
 /// </param>
 public Video (int pos, string location, int quality, VideoType format)
 {
     this.Position = pos;
     this.Location = location;
     this.Quality = quality;
     this.Format = format.ToString();
     this.IsAudioFile = false;
 }
Beispiel #32
0
        private static void CheckAndAddWhenFull(string startType, string decoded, bool[] CheckingData, int pos, ObservableCollection <VideoInformation> AllInfo, string url2, VideoType type2, string codes2, string fallbackhost2, string signature2, VideoQuality quality2)
        {
            /*         if (decoded.Contains(startType))
             *       {
             *           // reset if already exist.
             *           for (int i = 0; i < CheckingData.Length; i++)
             *           {
             *               CheckingData[i] = false;
             *           }
             *       }*/
            if (!CheckingData[pos])
            {
                CheckingData[pos] = true;

                foreach (bool x in CheckingData)
                {
                    if (!x)
                    {
                        return; // one not added yet
                    }
                }
                // All full
                AllInfo.Add(new VideoInformation(url2, type2, codes2, fallbackhost2, signature2, quality2));

                // reset required counter
                for (int i = 0; i < CheckingData.Length; i++)
                {
                    CheckingData[i] = false;
                }
            }
        }
 protected bool IsRippedMedia(VideoType type)
 {
     return type == VideoType.BluRay || type == VideoType.Dvd || type == VideoType.Iso || type == VideoType.HdDvd;
 }
Beispiel #34
0
 public Task ConvertAsync(VideoType vidType, AudioType audType, string videoToConvertFilePath, string outputFilePath)
 {
     return(Task.Run(() => Convert(vidType, audType, videoToConvertFilePath, outputFilePath)));
 }
Beispiel #35
0
 public void SendMessageVideo(string to, byte[] videoData, VideoType vidtype)
 {
     FMessage msg = this.getFmessageVideo(to, videoData, vidtype);
     if (msg != null)
     {
         this.SendMessage(msg);
     }
 }
Beispiel #36
0
        public void Convert(VideoType vidType, AudioType audType, string videoToConvertFilePath, string outputFilePath)
        {
            // http://www.mplayerhq.hu/DOCS/HTML/en/menc-feat-selecting-codec.html

            StringBuilder cmd = new StringBuilder();

            // mencoder.exe


            cmd.Append("-ovc");  // video codec for encoding
            cmd.Append(" ");

            bool lavcVideoSelected = false;
            bool lavcAudioSelected = false;

            if (vidType == VideoType.x264)
            {
                cmd.Append("x264");
            }
            else if (vidType == VideoType.xvid)
            {
                cmd.Append("xvid");
            }
            else
            {
                lavcVideoSelected = true;
                cmd.Append("lavc");  // use one of libavcodec's video codecs
            }
            cmd.Append(" ");

            cmd.Append("-oac");  // audio codec for encoding
            cmd.Append(" ");

            if (audType == AudioType.mp3)
            {
                cmd.Append("mp3lame");
            }
            else
            {
                lavcAudioSelected = true;
                cmd.Append("lavc");  // use one of libavcodec's audio codecs
            }
            cmd.Append(" ");


            cmd.Append('"' + videoToConvertFilePath + '"');
            cmd.Append(" ");

            if (vidType == VideoType.webm)
            {
                cmd.Append("-ffourcc");
                cmd.Append(" ");
                cmd.Append("VP80");
                cmd.Append(" ");
            }


            if (lavcAudioSelected == true || lavcVideoSelected == true)
            {
                cmd.Append("-lavcopts");
                cmd.Append(" ");
            }

            if (lavcVideoSelected)   // Using builtin codes from lavc

            // setup the selected video format
            {
                if (vidType == VideoType.webm)
                {
                    cmd.Append("vcodec=libvpx");
                }
                else if (vidType == VideoType.mpeg4)
                {
                    cmd.Append("vcodec=mpeg4");
                }
                else if (vidType == VideoType.wmv1)
                {
                    cmd.Append("vcodec=wmv1");
                }
                else if (vidType == VideoType.wmv2)
                {
                    cmd.Append("vcodec=wmv2");
                }
                cmd.Append(" ");
            }

            if (lavcAudioSelected)
            {
                // setup the selected audio format
                if (audType == AudioType.vorbis)
                {
                    cmd.Append("acodec=libvorbis");
                }
                else if (audType == AudioType.ac3)
                {
                    cmd.Append("acodec=ac3");
                }
                else if (audType == AudioType.flac)
                {
                    cmd.Append("acodec=flac");
                }
                else if (audType == AudioType.mp2)
                {
                    cmd.Append("acodec=mp2");
                }
                else if (audType == AudioType.wmav1)
                {
                    cmd.Append("acodec=wmav1");
                }
                else if (audType == AudioType.wmav2)
                {
                    cmd.Append("acodec=wmav2");
                }
                cmd.Append(" ");
            }

            cmd.Append("-vf harddup");  // avoid audio/video sync issues
            cmd.Append(" ");

            cmd.Append("-o");
            cmd.Append(" ");
            cmd.Append('"' + outputFilePath + '"');

            Convert(cmd.ToString());
        }
        static void Main(string[] args)
        {
            var options = GetConfig();

            TwitchToken = options.Token;
            GetUserInfo();

            var folder = Path.Combine(RootPath, "downloads");

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            string           line   = "";
            int              offset = 0;
            VideoType        type   = VideoType.All;
            List <VideoInfo> videos = GetVideos(type);

            while (!line.StartsWith("q"))
            {
                Console.Clear();
                Console.WriteLine($"Videos page {Math.Ceiling(offset / (double)PAGESIZE) + 1}");
                int i = 1;
                foreach (var vid in videos)
                {
                    Console.WriteLine($"{i++}. [{vid.created_at}] {vid._id}-{vid.title} ({new TimeSpan(0, 0, vid.length):hh\\:mm\\:ss})");
                }
                Console.WriteLine($"Enter 1-{PAGESIZE} to download specific, a to download page, n to get next page, p to get previous page, q to quit, t to change types:");
                line = Console.ReadLine();
                if (int.TryParse(line, out int index) && index > 0 && index <= PAGESIZE)
                {
                    var vid      = videos[index - 1];
                    var fileName = SanitizeFile($"[{vid.created_at}] {vid.title}-{vid._id}.ts");
                    var filePath = Path.Combine(folder, fileName);
                    DownloadVideo(vid._id, filePath);
                    Console.WriteLine("Press any key to continue");
                    Console.ReadKey();
                }
                else
                {
                    switch (line)
                    {
                    case "a":
                        foreach (var vid in videos)
                        {
                            var fileName = SanitizeFile($"[{vid.created_at}] {vid.title}-{vid._id}.ts");
                            var filePath = Path.Combine(folder, fileName);
                            DownloadVideo(vid._id, filePath);
                        }
                        Console.WriteLine("Press any key to continue");
                        Console.ReadKey();
                        break;

                    case "n":
                        if (videos.Count >= PAGESIZE)
                        {
                            offset += PAGESIZE;
                            videos  = GetVideos(type, offset: offset);
                        }
                        else
                        {
                            Console.WriteLine("No more pages after current. Press any key to continue");
                            Console.ReadKey();
                        }
                        break;

                    case "p":
                        if (offset > 0)
                        {
                            offset -= PAGESIZE;
                            videos  = GetVideos(type, offset: offset);
                        }
                        else
                        {
                            Console.WriteLine("No more pages before current. Press any key to continue");
                            Console.ReadKey();
                        }
                        break;

                    case "t":
                        Console.Clear();
                        Console.WriteLine("Select type of videos:");
                        Console.WriteLine("a. All");
                        Console.WriteLine("b. Past Broadcast");
                        Console.WriteLine("h. Highlight");
                        Console.WriteLine("u. Upload");
                        Console.WriteLine("p. Past Premiere");
                        line = Console.ReadLine();
                        type = line == "b" ? VideoType.Archive :
                               line == "h" ? VideoType.Highlight :
                               line == "u" ? VideoType.Upload :
                               line == "p" ? VideoType.PastPremiere :
                               VideoType.All;

                        offset = 0;
                        videos = GetVideos(type);
                        Console.WriteLine("Press any key to continue");
                        Console.ReadKey();
                        break;

                    default:
                        Console.WriteLine("Invalid option. Press any key to continue");
                        Console.ReadKey();
                        break;
                    }
                }
            }
        }
 public BigBlueButtonDocumentDeskShareVideoOptions(VideoType preferredVideoType, string videoElementSelector)
 {
     _preferredVideoType   = preferredVideoType;
     _videoElementSelector = videoElementSelector;
 }
Beispiel #39
0
        internal static List <string> getDownloadLinks(List <StringBuilder> reconstructedUrls, string videoFormat, int resolution, List <string> videoTitles)
        {
            List <string> downloadUrls = new List <string>();

            videoTitles.Capacity = 100;
            VideoType videotype = getVideoType(videoFormat);

            for (int i = 0; i < reconstructedUrls.Count; i++)
            {
                try
                {
                    var url = reconstructedUrls[i].ToString();
                    if (videoFormat.Equals("mp3", StringComparison.OrdinalIgnoreCase))
                    {
                        // http://www.youtubeinmp3.com/fetch/?format=text&video=http://www.youtube.com/watch?v=i62Zjga8JOM
                        var        requestUrl = " http://www.youtubeinmp3.com/fetch/?format=text&video=" + url;
                        WebRequest wrGETURL;
                        wrGETURL = WebRequest.Create(requestUrl);

                        //WebProxy myProxy = new WebProxy("myproxy", 80);
                        //myProxy.BypassProxyOnLocal = true;

                        //wrGETURL.Proxy = WebProxy.GetDefaultProxy();

                        Stream objStream;
                        objStream = wrGETURL.GetResponse().GetResponseStream();

                        StreamReader objReader = new StreamReader(objStream);

                        string sLine = "";

                        string response = objReader.ReadToEnd();
                        var    mp3Url   = response.Substring(response.IndexOf("=http://www.youtube.com"));


                        downloadUrls.Add(mp3Url);
                        Console.WriteLine(mp3Url);
                        //Select only one entry that matches the video type and resolution
                        break;
                    }
                    else
                    {
                        IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(url);

                        foreach (var video in videoInfos)
                        {
                            if ((video.Resolution == resolution) && (video.VideoType == videotype))
                            {
                                downloadUrls.Add(video.DownloadUrl + "&title=" + videoTitles[i]);
                                Console.WriteLine(video.DownloadUrl);
                                //Select only one entry that matches the video type and resolution
                                break;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }

            Console.WriteLine("--------------------------------------Download Urls--------------------------------------------");

            foreach (var item in downloadUrls)
            {
                Console.WriteLine(item.ToString());
            }

            return(downloadUrls);
        }
Beispiel #40
0
        /// <summary>
        /// 运行格式转换
        /// </summary>
        /// <param name="sourceFile">要转换文件绝对路径</param>
        /// <param name="destPath">转换结果存储的相对路径</param>
        /// <param name="videotype">要转换成的文件类型</param>
        /// <param name="createImage">是否生成截图</param>
        /// <returns>
        /// 执行成功返回空,否则返回错误信息
        /// </returns>
        public string Convert(string sourceFile, string destPath, string uniquename, VideoType videotype, bool createImage, bool getDuration)
        {
            //取得ffmpeg.exe的物理路径
            string ffmpeg = System.Web.HttpContext.Current.Server.MapPath(ffmpegpath);

            if (!File.Exists(ffmpeg))
            {
                return("找不到格式转换程序!");
            }
            if (!File.Exists(sourceFile))
            {
                return("找不到源文件!");
            }
            //string uniquename = FileHelper.GetUniqueFileName();
            string filename = uniquename + GetDiscription(videotype);

            if (!destPath.EndsWith(@"\"))
            {
                destPath = string.Format("{0}\\", destPath);
            }
            string destFile = HttpContext.Current.Server.MapPath(destPath + filename);

            //if (Path.GetExtension(sourceFile).ToLower() != GetDiscription(videotype).ToLower())
            //{
            System.Diagnostics.ProcessStartInfo FilestartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);
            FilestartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            /*ffmpeg参数说明
             * -i 1.avi   输入文件
             * -ab/-ac <比特率> 设定声音比特率,前面-ac设为立体声时要以一半比特率来设置,比如192kbps的就设成96,转换
             *  均默认比特率都较小,要听到较高品质声音的话建议设到160kbps(80)以上
             * -ar <采样率> 设定声音采样率,PSP只认24000
             * -b <比特率> 指定压缩比特率,似乎ffmpeg是自动VBR的,指定了就大概是平均比特率,比如768,1500这样的   --加了以后转换不正常
             * -r 29.97 桢速率(可以改,确认非标准桢率会导致音画不同步,所以只能设定为15或者29.97)
             * s 320x240 指定分辨率
             * 最后的路径为目标文件
             */
            FilestartInfo.Arguments = " -i " + sourceFile + " -ab 80 -ar 22050 -r 29.97 -s " + videosize + " " + destFile;
            //FilestartInfo.Arguments = "-y -i " + sourceFile + " -s 320x240 -vcodec h264 -qscale 4  -ar 24000 -f psp -muxvb 768 " + destFile;
            try
            {
                //转换
                System.Diagnostics.Process.Start(FilestartInfo);
                destVideo = destPath + filename;
            }
            catch
            {
                return("格式转换失败!");
            }
            //}
            //格式不需要转换则直接复制文件到目录
            //else
            //{
            //    File.Copy(sourceFile, destFile,true);
            //    destVideo = destPath + filename;
            //}
            //提取视频长度
            if (getDuration)
            {
                VideoLength = GetVideoDuration(ffmpeg, sourceFile);
            }
            //提取图片
            if (createImage)
            {
                //定义进程
                System.Diagnostics.ProcessStartInfo ImgstartInfo = new System.Diagnostics.ProcessStartInfo(ffmpeg);

                //截大图
                string imgpath = destPath + uniquename + ".jpg";// FileHelper.GetUniqueFileName(".jpg");
                ConvertImage(sourceFile, imgpath, imgsize, ImgstartInfo);

                //截小图
                imgpath   = destPath + uniquename + "_thumb.jpg";
                DestImage = ConvertImage(sourceFile, imgpath, "80*80", ImgstartInfo);
            }
            return("");
        }
Beispiel #41
0
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <returns>Task{MediaInfoResult}.</returns>
        private async Task <MediaInfo> GetMediaInfoInternal(string inputPath,
                                                            string primaryPath,
                                                            MediaProtocol protocol,
                                                            bool extractChapters,
                                                            string probeSizeArgument,
                                                            bool isAudio,
                                                            VideoType videoType,
                                                            bool forceEnableLogging,
                                                            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

            var process = _processFactory.Create(new ProcessOptions
            {
                CreateNoWindow  = true,
                UseShellExecute = false,

                // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
                RedirectStandardOutput = true,
                FileName  = FFProbePath,
                Arguments = string.Format(args, probeSizeArgument, inputPath).Trim(),

                IsHidden            = true,
                ErrorDialog         = false,
                EnableRaisingEvents = true
            });

            if (forceEnableLogging)
            {
                _logger.Info("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }
            else
            {
                _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
            }

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _ffProbeResourcePool.Release();

                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    //process.BeginErrorReadLine();

                    var result = _jsonSerializer.DeserializeFromStream <InternalMediaInfoResult>(process.StandardOutput.BaseStream);

                    if (result == null || (result.streams == null && result.format == null))
                    {
                        throw new Exception("ffprobe failed - streams and format are both null.");
                    }

                    if (result.streams != null)
                    {
                        // Normalize aspect ratio if invalid
                        foreach (var stream in result.streams)
                        {
                            if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.display_aspect_ratio = string.Empty;
                            }
                            if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.sample_aspect_ratio = string.Empty;
                            }
                        }
                    }

                    var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem, _memoryStreamProvider).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);

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

                    if (videoStream != null && !videoStream.IsInterlaced)
                    {
                        var isInterlaced = DetectInterlaced(mediaInfo, videoStream);

                        if (isInterlaced)
                        {
                            videoStream.IsInterlaced = true;
                        }
                    }

                    return(mediaInfo);
                }
                catch
                {
                    StopProcess(processWrapper, 100);

                    throw;
                }
                finally
                {
                    _ffProbeResourcePool.Release();
                }
            }
        }
Beispiel #42
0
        private static Exception ParseYouTubeStreamData(string response, bool SourceFromWebSourceCode, ObservableCollection <VideoInformation> AllInfo, bool DesktopMode)
        {
            // Make sure the HTML5 player is loaded correctly.


            // url, type, fallback_host, sig, quality
            bool[] CheckingData = { false, false, false, false, false };

            Exception eax = null;

            try
            {
                string[] indi = response.Split('&');
                //            throw new Exception();
                // For the Source Code based

                string       startType2 = null;
                string       codes2 = null, url2 = null, signature2 = null, fallbackhost2 = null;
                VideoType    type2    = VideoType.NULL;
                VideoQuality quality2 = VideoQuality.NULL;

                foreach (string x in indi)
                {
                    if (x.StartsWith("url_encoded_fmt_stream_map") || SourceFromWebSourceCode)
                    {
                        if (SourceFromWebSourceCode)
                        {
                            string esc1 = Uri.UnescapeDataString(x);
                            //Debug.WriteLine(esc1);
                            if (startType2 == null)
                            {
                                int equalIndex = esc1.IndexOf("=", 0);
                                if (equalIndex != -1)
                                {
                                    startType2 = esc1.Substring(0, equalIndex);
                                }
                            }

                            // Check for quality string, google is being sneaky..
                            int index    = 0;
                            int tmpindex = 0;
                            while (tmpindex >= 0 && tmpindex < esc1.Length && (tmpindex = esc1.IndexOf(",", tmpindex + 1)) > 0)
                            {
                                index = tmpindex;

                                string after = Uri.UnescapeDataString(esc1.Substring(index + 1, esc1.Length - (index + 1)));

                                bool found = false;

                                if (after.StartsWith("url="))
                                {
                                    ParseYouTubeInfoURL(startType2, after, CheckingData, AllInfo, out url2, type2, codes2, fallbackhost2, signature2, quality2);
                                    found = true;
                                }
                                else if (after.StartsWith("type="))
                                {
                                    ParseYouTubeInfoType(startType2, after, CheckingData, AllInfo, url2, out type2, out codes2, fallbackhost2, signature2, quality2);
                                    found = true;
                                }
                                else if (after.StartsWith("fallback_host="))
                                {
                                    ParseYouTubeInfo_FallBackHost(startType2, after, CheckingData, AllInfo, url2, type2, codes2, out fallbackhost2, signature2, quality2);
                                    found = true;
                                }
                                else if (after.StartsWith("sig=") || after.StartsWith("s=") || after.StartsWith("signature="))
                                {
                                    ParseYouTubeInfo_Signature(startType2, after, CheckingData, AllInfo, url2, type2, codes2, fallbackhost2, out signature2, quality2);
                                    found = true;
                                }
                                else if (after.StartsWith("size="))
                                {
                                    ParseYouTubeInfo_Quality(startType2, after, CheckingData, AllInfo, url2, type2, codes2, fallbackhost2, signature2, out quality2);
                                    found = true;
                                }
                                else if (after.StartsWith("quality="))
                                {
                                    ParseYouTubeInfo_Quality(startType2, after, CheckingData, AllInfo, url2, type2, codes2, fallbackhost2, signature2, out quality2);
                                    found = true;
                                }
                                else if (after.StartsWith("itag="))
                                {
                                    found = true;
                                }

                                // remove if required
                                if (found)
                                {
                                    esc1 = esc1.Substring(0, index);
                                }
                            }
                            string decoded = Uri.UnescapeDataString(esc1);

                            //                Debug.WriteLine(decoded);
                            if (decoded.StartsWith("url="))
                            {
                                ParseYouTubeInfoURL(startType2, decoded, CheckingData, AllInfo, out url2, type2, codes2, fallbackhost2, signature2, quality2);
                            }
                            else if (decoded.StartsWith("type="))
                            {
                                ParseYouTubeInfoType(startType2, decoded, CheckingData, AllInfo, url2, out type2, out codes2, fallbackhost2, signature2, quality2);
                            }
                            else if (decoded.StartsWith("fallback_host="))
                            {
                                ParseYouTubeInfo_FallBackHost(startType2, decoded, CheckingData, AllInfo, url2, type2, codes2, out fallbackhost2, signature2, quality2);
                            }
                            else if (decoded.StartsWith("sig=") || decoded.StartsWith("s=") || decoded.StartsWith("signature="))
                            {
                                ParseYouTubeInfo_Signature(startType2, decoded, CheckingData, AllInfo, url2, type2, codes2, fallbackhost2, out signature2, quality2);
                            }
                            else if (decoded.StartsWith("quality="))
                            {
                                ParseYouTubeInfo_Quality(startType2, decoded, CheckingData, AllInfo, url2, type2, codes2, fallbackhost2, signature2, out quality2);
                            }
                            else if (decoded.StartsWith("size="))
                            {
                                ParseYouTubeInfo_Quality(startType2, decoded, CheckingData, AllInfo, url2, type2, codes2, fallbackhost2, signature2, out quality2);
                            }
                        }
                        else
                        {
                            string       codes = null, url = null, signature = null, fallbackhost = null;
                            string       startType = null;
                            VideoType    type      = VideoType.NULL;
                            VideoQuality quality   = VideoQuality.NULL;

                            string   header = "url_encoded_fmt_stream_map=";
                            string   x3     = Uri.UnescapeDataString(WebUtility.HtmlDecode(x.Substring(header.Length, x.Length - header.Length)));
                            string[] indi2  = x3.Split('&');

                            //Debug.WriteLine(x3);

                            foreach (string x2 in indi2)
                            {
                                string esc1 = Uri.UnescapeDataString(x2);
                                //Debug.WriteLine(esc1);
                                if (startType == null)
                                {
                                    int equalIndex = esc1.IndexOf("=", 0);
                                    if (equalIndex != -1)
                                    {
                                        startType = esc1.Substring(0, equalIndex);
                                    }
                                }

                                // Check for quality string, google is being sneaky..
                                int index    = 0;
                                int tmpindex = 0;
                                while (tmpindex >= 0 && tmpindex < esc1.Length && (tmpindex = esc1.IndexOf(",", tmpindex + 1)) > 0)
                                {
                                    index = tmpindex;

                                    string after = esc1.Substring(index + 1, esc1.Length - (index + 1));
                                    after = Uri.UnescapeDataString(after);

                                    bool found = false;

                                    if (after.StartsWith("url="))
                                    {
                                        ParseYouTubeInfoURL(startType, after, CheckingData, AllInfo, out url, type, codes, fallbackhost, signature, quality);
                                        found = true;
                                    }
                                    else if (after.StartsWith("type="))
                                    {
                                        ParseYouTubeInfoType(startType, after, CheckingData, AllInfo, url, out type, out codes, fallbackhost, signature, quality);
                                        found = true;
                                    }
                                    else if (after.StartsWith("fallback_host="))
                                    {
                                        ParseYouTubeInfo_FallBackHost(startType, after, CheckingData, AllInfo, url, type, codes, out fallbackhost, signature, quality);
                                        found = true;
                                    }
                                    else if (after.StartsWith("sig=") || after.StartsWith("s=") || after.StartsWith("signature="))
                                    {
                                        ParseYouTubeInfo_Signature(startType, after, CheckingData, AllInfo, url, type, codes, fallbackhost, out signature, quality);
                                        found = true;
                                    }
                                    else if (after.StartsWith("quality="))
                                    {
                                        ParseYouTubeInfo_Quality(startType, after, CheckingData, AllInfo, url, type, codes, fallbackhost, signature, out quality);
                                        found = true;
                                    }
                                    else if (after.StartsWith("itag="))
                                    {
                                        found = true;
                                    }

                                    // remove if required
                                    if (found)
                                    {
                                        esc1 = esc1.Substring(0, index);
                                    }
                                }
                                string esc2    = Uri.UnescapeDataString(esc1);
                                string decoded = esc2;

                                if (decoded.StartsWith("url="))
                                {
                                    ParseYouTubeInfoURL(startType, decoded, CheckingData, AllInfo, out url, type, codes, fallbackhost, signature, quality);
                                }
                                else if (decoded.StartsWith("type="))
                                {
                                    ParseYouTubeInfoType(startType, decoded, CheckingData, AllInfo, url, out type, out codes, fallbackhost, signature, quality);
                                }
                                else if (decoded.StartsWith("fallback_host="))
                                {
                                    ParseYouTubeInfo_FallBackHost(startType, decoded, CheckingData, AllInfo, url, type, codes, out fallbackhost, signature, quality);
                                }
                                else if (decoded.StartsWith("sig=") || decoded.StartsWith("s=") || decoded.StartsWith("signature="))
                                {
                                    ParseYouTubeInfo_Signature(startType, decoded, CheckingData, AllInfo, url, type, codes, fallbackhost, out signature, quality);
                                }
                                else if (decoded.StartsWith("quality="))
                                {
                                    ParseYouTubeInfo_Quality(startType, decoded, CheckingData, AllInfo, url, type, codes, fallbackhost, signature, out quality);
                                }
                                else if (decoded.StartsWith("itag="))
                                {
                                    // empty
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ecs)
            {
                //AzureOperation.InsertReportItem("APIs_VideoStream.ParseYouTubeStreamData", ecs.ToString());
                eax = ecs;
                Debug.WriteLine(ecs.ToString());
            }
            return(eax);
        }
 public VideoProcessor(VideoType type)
 {
     videoType = type;
 }
        /// <summary>
        ///     Returns VideoInfo of the highest convertiable url of this youtube video
        /// </summary>
        public static async Task<VideoInfo> GetHighestVideoQualityDownloadUrlAsync(string url, VideoType type = VideoType.Mp4) {
            if (url == null || NormalizeYoutubeUrl(url) == null)
                throw new ArgumentNullException(nameof(url));
            var urls = await GetDownloadUrlsAsync(new YoutubeContext(url));
            var video = urls.Where(vi => vi.VideoType == type).OrderByDescending(info => info.Resolution).FirstOrDefault();

            if (video?.RequiresDecryption == true)
                DecryptDownloadUrl(video);
            return video;
        }
Beispiel #45
0
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="primaryPath">The primary path.</param>
        /// <param name="protocol">The protocol.</param>
        /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
        /// <param name="probeSizeArgument">The probe size argument.</param>
        /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MediaInfoResult}.</returns>
        /// <exception cref="System.ApplicationException">ffprobe failed - streams and format are both null.</exception>
        private async Task<Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
            string primaryPath,
            MediaProtocol protocol,
            bool extractChapters,
            string probeSizeArgument,
            bool isAudio,
            VideoType videoType,
            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

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

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.   
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    RedirectStandardInput = true,
                    FileName = FFProbePath,
                    Arguments = string.Format(args,
                    probeSizeArgument, inputPath).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _ffProbeResourcePool.Release();

                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    process.BeginErrorReadLine();

                    var result = _jsonSerializer.DeserializeFromStream<InternalMediaInfoResult>(process.StandardOutput.BaseStream);

                    if (result.streams == null && result.format == null)
                    {
                        throw new ApplicationException("ffprobe failed - streams and format are both null.");
                    }

                    if (result.streams != null)
                    {
                        // Normalize aspect ratio if invalid
                        foreach (var stream in result.streams)
                        {
                            if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.display_aspect_ratio = string.Empty;
                            }
                            if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.sample_aspect_ratio = string.Empty;
                            }
                        }
                    }

                    var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);

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

                    if (videoStream != null)
                    {
                        var isInterlaced = await DetectInterlaced(mediaInfo, videoStream, inputPath, probeSizeArgument).ConfigureAwait(false);

                        if (isInterlaced)
                        {
                            videoStream.IsInterlaced = true;
                        }
                    }

                    return mediaInfo;
                }
                catch
                {
                    StopProcess(processWrapper, 100, true);

                    throw;
                }
                finally
                {
                    _ffProbeResourcePool.Release();
                }
            }
        }
Beispiel #46
0
        private void DownloadVideo(IEnumerable <VideoInfo> videoInfos, int resolution, int position, VideoType format)
        {
            /*
             * Select the first .mp4 video with 360p resolution
             */
            VideoInfo video = videoInfos
                              .First(info => info.VideoType == format && info.Resolution == resolution);

            /*
             * If the video has a decrypted signature, decipher it
             */
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            /*
             * Create the video downloader.
             * The first argument is the video to download.
             * The second argument is the path to save the video file.
             */

            var videoName = RemoveIllegalPathCharacters(video.Title) + video.VideoExtension;

            var videoPath = Path.Combine(MainForm.TempDownloadLocation, videoName);

            var finalPath = Path.Combine(MainForm.DownloadLocation, videoName);

            if (!File.Exists(finalPath))
            {
                var videoDownloader = new VideoDownloader(video, videoPath);

                // Register the ProgressChanged event and print the current progress
                videoDownloader.DownloadProgressChanged += (sender, args) => MainForm.DownloadFinishedPercent = (int)args.ProgressPercentage;

                /*
                 * Execute the video downloader.
                 * For GUI applications note, that this method runs synchronously.
                 */
                videoDownloader.Execute();

                File.Move(videoPath, finalPath);
            }
            else
            {
                MainForm.StatusBar = string.Format(CultureInfo.InstalledUICulture, "{0}({1}) already exists! Download process has been aborted and considered successful.", Truncate(video.Title, 18), position).ToLower(CultureInfo.InstalledUICulture);
            }
        }
Beispiel #47
0
        /// <summary>
        /// Gets the media info internal.
        /// </summary>
        /// <param name="inputPath">The input path.</param>
        /// <param name="primaryPath">The primary path.</param>
        /// <param name="protocol">The protocol.</param>
        /// <param name="extractChapters">if set to <c>true</c> [extract chapters].</param>
        /// <param name="extractKeyFrameInterval">if set to <c>true</c> [extract key frame interval].</param>
        /// <param name="probeSizeArgument">The probe size argument.</param>
        /// <param name="isAudio">if set to <c>true</c> [is audio].</param>
        /// <param name="videoType">Type of the video.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MediaInfoResult}.</returns>
        /// <exception cref="System.ApplicationException"></exception>
        private async Task <Model.MediaInfo.MediaInfo> GetMediaInfoInternal(string inputPath,
                                                                            string primaryPath,
                                                                            MediaProtocol protocol,
                                                                            bool extractChapters,
                                                                            bool extractKeyFrameInterval,
                                                                            string probeSizeArgument,
                                                                            bool isAudio,
                                                                            VideoType videoType,
                                                                            CancellationToken cancellationToken)
        {
            var args = extractChapters
                ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format"
                : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format";

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

                    // Must consume both or ffmpeg may hang due to deadlocks. See comments below.
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,
                    FileName  = FFProbePath,
                    Arguments = string.Format(args,
                                              probeSizeArgument, inputPath).Trim(),

                    WindowStyle = ProcessWindowStyle.Hidden,
                    ErrorDialog = false
                },

                EnableRaisingEvents = true
            };

            _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);

            using (var processWrapper = new ProcessWrapper(process, this, _logger))
            {
                await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    StartProcess(processWrapper);
                }
                catch (Exception ex)
                {
                    _ffProbeResourcePool.Release();

                    _logger.ErrorException("Error starting ffprobe", ex);

                    throw;
                }

                try
                {
                    process.BeginErrorReadLine();

                    var result = _jsonSerializer.DeserializeFromStream <InternalMediaInfoResult>(process.StandardOutput.BaseStream);

                    if (result.streams == null && result.format == null)
                    {
                        throw new ApplicationException("ffprobe failed - streams and format are both null.");
                    }

                    if (result.streams != null)
                    {
                        // Normalize aspect ratio if invalid
                        foreach (var stream in result.streams)
                        {
                            if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.display_aspect_ratio = string.Empty;
                            }
                            if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase))
                            {
                                stream.sample_aspect_ratio = string.Empty;
                            }
                        }
                    }

                    var mediaInfo = new ProbeResultNormalizer(_logger, FileSystem).GetMediaInfo(result, videoType, isAudio, primaryPath, protocol);

                    if (extractKeyFrameInterval && mediaInfo.RunTimeTicks.HasValue)
                    {
                        if (ConfigurationManager.Configuration.EnableVideoFrameByFrameAnalysis && mediaInfo.Size.HasValue)
                        {
                            foreach (var stream in mediaInfo.MediaStreams)
                            {
                                if (EnableKeyframeExtraction(mediaInfo, stream))
                                {
                                    try
                                    {
                                        stream.KeyFrames = await GetKeyFrames(inputPath, stream.Index, cancellationToken).ConfigureAwait(false);
                                    }
                                    catch (OperationCanceledException)
                                    {
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.ErrorException("Error getting key frame interval", ex);
                                    }
                                }
                            }
                        }
                    }

                    return(mediaInfo);
                }
                catch
                {
                    StopProcess(processWrapper, 100, true);

                    throw;
                }
                finally
                {
                    _ffProbeResourcePool.Release();
                }
            }

            throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath));
        }
Beispiel #48
0
 public static FileInfo OutputLocation(this FileInfo file, VideoType type)
 {
     return(OutputLocation(file, type, "_converted"));
 }
Beispiel #49
0
        public InternalItemsQuery()
        {
            GroupByPresentationUniqueKey = true;
            EnableTotalRecordCount = true;

            AlbumNames = new string[] { };
            ArtistNames = new string[] { };
            
            BlockUnratedItems = new UnratedItem[] { };
            Tags = new string[] { };
            OfficialRatings = new string[] { };
            SortBy = new string[] { };
            MediaTypes = new string[] { };
            IncludeItemTypes = new string[] { };
            ExcludeItemTypes = new string[] { };
            Genres = new string[] { };
            Studios = new string[] { };
            StudioIds = new string[] { };
            GenreIds = new string[] { };
            ImageTypes = new ImageType[] { };
            VideoTypes = new VideoType[] { };
            Years = new int[] { };
            PersonTypes = new string[] { };
            PersonIds = new string[] { };
            ChannelIds = new string[] { };
            ItemIds = new string[] { };
            AncestorIds = new string[] { };
            TopParentIds = new string[] { };
            ExcludeTags = new string[] { };
            ExcludeInheritedTags = new string[] { };
            LocationTypes = new LocationType[] { };
            ExcludeLocationTypes = new LocationType[] { };
            PresetViews = new string[] { };
            SourceTypes = new SourceType[] { };
            ExcludeSourceTypes = new SourceType[] { };
            TrailerTypes = new TrailerType[] { };
            AirDays = new DayOfWeek[] { };
            SeriesStatuses = new SeriesStatus[] { };
        }
Beispiel #50
0
        private void SearchChannel(string channel, VideoType videoType, LoadLimitType loadLimit, DateTime loadFrom, DateTime loadTo, int loadLastVods)
        {
            if (string.IsNullOrWhiteSpace(channel))
            {
                throw new ArgumentNullException(nameof(channel));
            }

            string channelId = GetChannelIdByName(channel);

            ObservableCollection <TwitchVideo> videos = new ObservableCollection <TwitchVideo>();

            string broadcastTypeParam = null;

            if (videoType == VideoType.Broadcast)
            {
                broadcastTypeParam = "archive";
            }
            else if (videoType == VideoType.Highlight)
            {
                broadcastTypeParam = "highlight";
            }
            else if (videoType == VideoType.Upload)
            {
                broadcastTypeParam = "upload";
            }
            else
            {
                throw new ApplicationException("Unsupported video type '" + videoType.ToString() + "'");
            }

            string channelVideosUrl = string.Format(CHANNEL_VIDEOS_URL, channelId);

            DateTime fromDate = DateTime.Now;
            DateTime toDate   = DateTime.Now;

            if (loadLimit == LoadLimitType.Timespan)
            {
                fromDate = loadFrom;
                toDate   = loadTo;
            }

            int offset = 0;
            int total  = 0;
            int sum    = 0;

            bool stop = false;

            do
            {
                using (WebClient webClient = CreatePublicApiWebClient())
                {
                    webClient.QueryString.Add("broadcast_type", broadcastTypeParam);
                    webClient.QueryString.Add("limit", TWITCH_MAX_LOAD_LIMIT.ToString());
                    webClient.QueryString.Add("offset", offset.ToString());

                    string result = webClient.DownloadString(channelVideosUrl);

                    JObject videosResponseJson = JObject.Parse(result);

                    if (videosResponseJson != null)
                    {
                        if (total == 0)
                        {
                            total = videosResponseJson.Value <int>("_total");
                        }

                        foreach (JObject videoJson in videosResponseJson.Value <JArray>("videos"))
                        {
                            sum++;

                            if (videoJson.Value <string>("_id").StartsWith("v"))
                            {
                                TwitchVideo video = ParseVideo(videoJson);

                                if (loadLimit == LoadLimitType.LastVods)
                                {
                                    videos.Add(video);

                                    if (sum >= loadLastVods)
                                    {
                                        stop = true;
                                        break;
                                    }
                                }
                                else
                                {
                                    DateTime recordedDate = video.RecordedDate;

                                    if (recordedDate.Date >= fromDate.Date && recordedDate.Date <= toDate.Date)
                                    {
                                        videos.Add(video);
                                    }

                                    if (recordedDate.Date < fromDate.Date)
                                    {
                                        stop = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }

                offset += TWITCH_MAX_LOAD_LIMIT;
            } while (!stop && sum < total);

            Videos = videos;
        }
Beispiel #51
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ItemQuery" /> class.
        /// </summary>
        public ItemQuery()
        {
            LocationTypes = new LocationType[] { };
            ExcludeLocationTypes = new LocationType[] { };
            
            SortBy = new string[] { };

            Filters = new ItemFilter[] {};

            Fields = new ItemFields[] {};

            MediaTypes = new string[] {};

            VideoTypes = new VideoType[] {};

            Genres = new string[] { };
            Studios = new string[] { };
            IncludeItemTypes = new string[] { };
            ExcludeItemTypes = new string[] { };
            Years = new int[] { };
            PersonTypes = new string[] { };
            Ids = new string[] { };
            Artists = new string[] { };

            ImageTypes = new ImageType[] { };
            AirDays = new DayOfWeek[] { };
            SeriesStatuses = new SeriesStatus[] { };
        }
Beispiel #52
0
        //删除文件
        protected void btnDel_Click(object sender, EventArgs e)
        {
            ResourceEntity re = null;
            Resource       r  = new Resource();

            if (ViewState["model"] != null)
            {
                re = ViewState["model"] as ResourceEntity;
            }
            else
            {
                re = r.GetResourceInfoByItemId(this.Hidden_ItemId.Value);
            }

            string ItemSerialNum = "";
            string ImageType     = "";
            string str           = "";//判断170图片或者400图片有没有被删除

            ItemSerialNum = lb_ItemSerialNum.Text;
            //ImageType = lb_ImageType.Text;
            //bool isValidate = QJVRMS.Business.ImageStorageClass.DeleteImageStorage(new Guid(this.Hidden_ItemId.Value));

            bool   isValidate       = Resource.DeleteResource(re.ItemId);
            string attachmentFolder = string.Empty;

            string sourceFolder      = string.Empty;
            string attachmentsFolder = string.Empty;

            if (re.ResourceType.ToLower().Equals("image"))
            {
                string _170Folder;
                string _400Folder;

                ImageType obj = new ImageType();
                //yangguang
                //sourceFolder = obj.SourcePath;
                //attachmentsFolder = obj.SourcePath;
                //_170Folder = obj.PreviewPath_170;
                //_400Folder = obj.PreviewPath_400;

                //sourceFolder = Path.Combine(sourceFolder, re.FolderName);
                //_170Folder = Path.Combine(_170Folder, re.FolderName);
                //_400Folder = Path.Combine(_400Folder, re.FolderName);

                //try {
                //    File.Delete(Path.Combine(sourceFolder, re.ServerFileName));
                //    File.Delete(Path.Combine(_170Folder, re.ServerFileName));
                //    File.Delete(Path.Combine(_400Folder, re.ServerFileName));
                //}
                //catch { }
                try {
                    File.Delete(obj.GetSourcePath(re.FolderName, re.ServerFileName));
                    attachmentsFolder = obj.SourcePaths[obj.PathNumber].Trim();
                    File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "170"));
                    File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "400"));
                }
                catch { }
            }
            else if (re.ResourceType.ToLower().Equals("video"))
            {
                string _previewPolder = CommonInfo.VideoPreviewPath;

                VideoType obj = new VideoType();
                //sourceFolder = obj.SourcePath;
                //attachmentsFolder = obj.SourcePath;
                //_previewPolder = obj.PreviewPath;

                //try {
                //    File.Delete(Path.Combine(sourceFolder, re.ServerFileName));
                //    File.Delete(Path.Combine(Path.Combine(Path.Combine(_previewPolder, "flv"), re.FolderName), re.ServerFileName));
                //    File.Delete(Path.Combine(Path.Combine(Path.Combine(_previewPolder, "image"), re.FolderName), re.ServerFileName));
                //    File.Delete(Path.Combine(Path.Combine(Path.Combine(_previewPolder, "smallflv"), re.FolderName), re.ServerFileName));
                //}
                //catch {

                //}
                try {
                    File.Delete(obj.GetSourcePath(string.Empty, re.ServerFileName));
                    attachmentsFolder = obj.SourcePaths[obj.PathNumber].Trim();
                    File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "flv"));
                    File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "image"));
                    File.Delete(obj.GetPreviewPath(re.FolderName, re.ServerFileName, "smallflv"));
                }
                catch {
                }
            }

            //sourceFolder = Path.Combine(sourceFolder, CurrentUser.UserLoginName);
            //sourceFolder = Path.Combine(sourceFolder, WebUI.UIBiz.CommonInfo.AttachFolder);

            #region  除物理文件 by ciqq 2010-4-2
            //SlImageRootPath = WebUI.UIBiz.CommonInfo.SlImageRootPath170;
            //if (Directory.Exists(SlImageRootPath + "\\" + CurrentUser.UserLoginName))
            //{
            //    File.Delete(SlImageRootPath + "\\" + CurrentUser.UserLoginName + "\\" + ItemSerialNum + ImageType);
            //    str = "170目录下的图片已被删除!";
            //}
            //SlImageRootPath = WebUI.UIBiz.CommonInfo.SlImageRootPath400;

            //if (Directory.Exists(SlImageRootPath + "\\" + CurrentUser.UserLoginName))
            //{
            //    File.Delete(SlImageRootPath + "\\" + CurrentUser.UserLoginName + "\\" + ItemSerialNum + ImageType);
            //    str += "400目录下的图片已被删除!";
            //}
            //SlImageRootPath = WebUI.UIBiz.CommonInfo.ImageRootPath;
            //if (Directory.Exists(SlImageRootPath + "\\" + CurrentUser.UserLoginName))
            //{
            //    File.Delete(SlImageRootPath + "\\" + CurrentUser.UserLoginName + "\\" + ItemSerialNum + ImageType);
            //    str += "Source目录下的图片已被删除!";
            //}

            //删除所有的附件
            //string sourceFolder = Path.Combine(WebUI.UIBiz.CommonInfo.ImageRootPath, this.hiFolder.Value);
            string fileName = "";
            attachmentsFolder = Path.Combine(attachmentsFolder, re.FolderName);
            attachmentsFolder = Path.Combine(attachmentsFolder, UIBiz.CommonInfo.AttachFolder);
            for (int i = 0; i < this.attList.Rows.Count; i++)
            {
                fileName = this.attList.DataKeys[i].Values[1].ToString();
                fileName = Path.Combine(attachmentsFolder, fileName);
                try {
                    File.Delete(fileName);
                }
                catch (Exception ex) {
                    LogWriter.WriteExceptionLog(ex);
                }
            }
            //foreach (GridViewRow gvr in this.attList.Rows) {
            //    fileName = Path.Combine(attachmentFolder, gvr.Cells[0].Text);

            //    try {
            //        File.Delete(fileName);
            //    }
            //    catch (Exception ex) {
            //        LogWriter.WriteExceptionLog(ex);
            //    }
            //}
            #endregion


            LogEntity model = new LogEntity();
            model.id           = Guid.NewGuid();
            model.userId       = CurrentUser.UserId;
            model.userName     = CurrentUser.UserLoginName;
            model.EventType    = ((int)LogType.DeleteResource).ToString();
            model.EventResult  = "成功";
            model.EventContent = "图片序号:" + re.ItemSerialNum;
            model.IP           = HttpContext.Current.Request.UserHostAddress;
            model.AddDate      = DateTime.Now;
            new Logs().Add(model);


            Response.Write("<script language='javascript'>window.close();</script>");
            Response.End();
        }
        public void ParseVideoType_ReturnsCorrectString(VideoType videoType, string expected)
        {
            //act
            var result = EnumFactory.ParseVideoType(videoType);

            //assert
            result.Should().Be(expected);
        }
 protected bool IsRippedMedia(VideoType type)
 {
     return(type == VideoType.BluRay || type == VideoType.Dvd || type == VideoType.Iso || type == VideoType.HdDvd);
 }
Beispiel #55
0
 public void SendMessageBroadcastVideo(string[] recipients, byte[] VideoData, VideoType vidtype)
 {
     string to;
     List<string> foo = new List<string>();
     foreach (string s in recipients)
     {
         foo.Add(GetJID(s));
     }
     to = string.Join(",", foo.ToArray());
     FMessage msg = this.getFmessageVideo(to, VideoData, vidtype);
     if (msg != null)
     {
         this.SendMessage(msg);
     }
 }
Beispiel #56
0
 /// <summary>
 /// 选择要采集的视频类型(注:未注册不支持Unity Camera)
 /// </summary>
 /// <param name="type">  DeviceCamera是外表摄像头的画面 UnityCamera是Unity Camera渲染的画面</param>
 /// <param name="captureCamera"></param>
 public void SetVideoCaptureType(VideoType type, Camera captureCamera)
 {
     UnityChatSDK.Instance.SetVideoCaptureType(type, captureCamera);
 }
Beispiel #57
0
        protected FMessage getFmessageVideo(string to, byte[] videoData, VideoType vidtype)
        {
            to = GetJID(to);
            string type = string.Empty;
            string extension = string.Empty;
            switch (vidtype)
            {
                case VideoType.MOV:
                    type = "video/quicktime";
                    extension = "mov";
                    break;
                case VideoType.AVI:
                    type = "video/x-msvideo";
                    extension = "avi";
                    break;
                default:
                    type = "video/mp4";
                    extension = "mp4";
                    break;
            }

            //create hash
            string filehash = string.Empty;
            using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
            {
                byte[] raw = sha.ComputeHash(videoData);
                filehash = Convert.ToBase64String(raw);
            }

            //request upload
            WaUploadResponse response = this.UploadFile(filehash, "video", videoData.Length, videoData, to, type, extension);

            if (response != null && !String.IsNullOrEmpty(response.url))
            {
                //send message
                FMessage msg = new FMessage(to, true) {
                    media_wa_type = FMessage.Type.Video,
                    media_mime_type = response.mimetype,
                    media_name = response.url.Split('/').Last(),
                    media_size = response.size,
                    media_url = response.url,
                    media_duration_seconds = response.duration
                };
                return msg;
            }
            return null;
        }
Beispiel #58
0
        private static void ParseYouTubeInfoURL(string startType, string decoded, bool[] CheckingData, ObservableCollection <VideoInformation> AllInfo, out string url, VideoType type, string codes, string fallbackhost, string signature, VideoQuality quality)
        {
            //Debug.WriteLine(decoded);

            url = decoded.Substring(4, decoded.Length - 4);

            if (AllInfo.Count > 0)
            {
                foreach (VideoInformation info in AllInfo)
                {
                    if (info.URL == null)
                    {
                        info.URL = url;
                        return;
                    }
                }
            }
            AllInfo.Add(new VideoInformation(url, VideoType.NULL, null, null, null, VideoQuality.NULL));

            //         CheckAndAddWhenFull(startType, decoded, CheckingData, 0, AllInfo, url, type, codes, fallbackhost, signature, quality);
        }
        /// <summary>
        ///     Returns VideoInfo of the highest convertiable url of this youtube video
        /// </summary>
        public static async Task FindHighestVideoQualityDownloadUrlAsync(this YoutubeContext context, VideoType type = VideoType.Mp4) {
            if (context == null)
                throw new ArgumentNullException(nameof(context));
            var urls = await GetDownloadUrlsAsync(context);
            context.VideoInfo = urls.Where(vi => vi.VideoType == type).OrderByDescending(info => info.Resolution).FirstOrDefault();

            if (context.VideoInfo?.RequiresDecryption == true)
                DecryptDownloadUrl(context.VideoInfo);
        }
Beispiel #60
0
        public Model.MediaInfo.MediaInfo GetMediaInfo(InternalMediaInfoResult data, VideoType videoType, bool isAudio, string path, MediaProtocol protocol)
        {
            var info = new Model.MediaInfo.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))
                {
                    info.Bitrate = int.Parse(data.format.bit_rate, _usCulture);
                }
            }

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

                var tags = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

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

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

                    if (audioStream != null && audioStream.tags != null)
                    {
                        foreach (var pair in audioStream.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;
                    }
                }

                SetAudioInfoFromTags(info, tags);
            }
            else
            {
                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 videoStream = info.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);

                if (videoStream != null && videoType == VideoType.VideoFile)
                {
                    UpdateFromMediaInfo(info, videoStream);
                }
            }

            return(info);
        }