Example #1
0
        private async Task DownloadFromUrl(AudioQuality audioQuality)
        {
            string url = Helpers.TakeInput("Enter URL: ");

            string[] urlMatches = Regex.Split(url, @"https?:\/\/www\.deezer\..+\/(\w+)\/(\d+)"); // ty smloadr for the regex

            if (urlMatches.Length < 3)
            {
                Helpers.RedMessage("Invalid URL");
                return;
            }

            string type = urlMatches[1];
            string id   = urlMatches[2];

            var deezerDownloader = new DeezerDownloader(_deezerHttp, audioQuality);

            switch (type)
            {
            case "track":
                await deezerDownloader.ProcessTrack(id);

                Console.Write("\n");
                break;

            case "artist":
                await deezerDownloader.ProcessArtist(id);

                break;

            case "playlist":
                await deezerDownloader.ProcessPlaylist(id);

                break;

            case "album":
                await deezerDownloader.ProcessAlbum(id);

                break;

            default:
                Helpers.RedMessage($"{type} is an unsupported type");
                break;
            }
        }
Example #2
0
        /// <summary>
        ///     Convert file to a specified format.
        /// </summary>
        /// <param name="type">Output format.</param>
        /// <param name="output">Output location.</param>
        /// <param name="speed">MP4 encoding speed (applies only to mp4 format). Faster results in lower quality.</param>
        /// <param name="size">Aspect ratio of the output video file.</param>
        /// <param name="audio">Audio quality of the output video file.</param>
        /// <param name="multithread">Tell FFMpeg to use multithread in the conversion process.</param>
        /// <param name="tryToPurge">
        ///     Flag original file purging after conversion is done (Will not result in exception if file is
        ///     readonly or missing.).
        /// </param>
        /// <returns>Video information object with the new video file.</returns>
        public VideoInfo ConvertTo(VideoType type, FileInfo output, Speed speed = Speed.SuperFast,
                                   VideoSize size  = VideoSize.Original, AudioQuality audio = AudioQuality.Normal, bool multithread = false,
                                   bool tryToPurge = false)
        {
            bool success;

            FFmpeg.OnProgress += OnConversionProgress;
            switch (type)
            {
            case VideoType.Mp4:
                success = FFmpeg.ToMp4(this, output, speed, size, audio, multithread);
                break;

            case VideoType.Ogv:
                success = FFmpeg.ToOgv(this, output, size, audio, multithread);
                break;

            case VideoType.Ts:
                success = FFmpeg.ToTs(this, output);
                break;

            default:
                throw new ArgumentException("Video type is not supported yet!");
            }

            if (!success)
            {
                throw new OperationCanceledException("The conversion process could not be completed.");
            }

            if (tryToPurge)
            {
                try
                {
                    if (Exists)
                    {
                        Delete();
                    }
                } catch { } // do nothing if file is locked
            }

            FFmpeg.OnProgress -= OnConversionProgress;

            return(FromFileInfo(output));
        }
Example #3
0
        public override void SaveSettings()
        {
            if (InputConfigs.Count > 0 && SelectedConfigIndex >= 0 && SelectedConfigIndex < InputConfigs.Count)
            {
                AudioQuality selected = InputConfigs[SelectedConfigIndex];
                Settings.Current.Frequency = selected.Frequency;
                Settings.Current.Bits      = selected.Bits;
            }

            if (OutputDevices.Count > 0 && SelectedOutputIndex >= 0 && SelectedOutputIndex < OutputDevices.Count)
            {
                Settings.Current.OutputAudioDevice = OutputDevices[SelectedOutputIndex];
            }

            if (InputDevices.Count > 0 && SelectedInputIndex >= 0 && SelectedInputIndex < InputDevices.Count)
            {
                Settings.Current.InputAudioDevice = InputDevices[selectedInputIndex];
            }

            if (!string.Equals(Localizer.Instance.Localize(PressTheKeyKey), SelectButtonName))
            {
                Settings.Current.RecorderKey = (Keys)Enum.Parse(typeof(Keys), SelectButtonName);
            }

            try
            {
                ClientModel.Recorder.SetOptions(Settings.Current.InputAudioDevice, InputConfigs[SelectedConfigIndex]);
                ClientModel.Player.SetOptions(Settings.Current.OutputAudioDevice);
            }
            catch (ModelException me)
            {
                ClientModel.Player.Dispose();
                ClientModel.Recorder.Dispose();

                if (me.Code != ErrorCode.AudioNotEnabled)
                {
                    throw;
                }
                else
                {
                    var msg = Localizer.Instance.Localize(MainViewModel.AudioInitializationFailedKey);
                    MessageBox.Show(msg, MainViewModel.ProgramName, MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }
Example #4
0
        private static int GetTargetBitrate(AudioQuality quality)
        {
            // https://wiki.xiph.org/Opus_Recommended_Settings#Recommended_Bitrates
            switch (quality)
            {
            case AudioQuality.Low:
                return(10000);

            case AudioQuality.Medium:
                return(17000);

            case AudioQuality.High:
                return(24000);

            default:
                throw new ArgumentOutOfRangeException("quality", quality, null);
            }
        }
Example #5
0
        public VoiceSettings()
        {
            _quality   = AudioQuality.Medium;
            _frameSize = FrameSize.Medium;
            _forwardErrorCorrection = Convert.ToInt32(true);

            _denoiseAmount = (int)NoiseSuppressionLevels.High;

            _aecAmount                = (int)AecSuppressionLevels.Disabled;
            _aecDelayAgnostic         = Convert.ToInt32(true);
            _aecExtendedFilter        = Convert.ToInt32(true);
            _aecRefinedAdaptiveFilter = Convert.ToInt32(true);

            _aecmRoutingMode  = (int)AecmRoutingMode.Disabled;
            _aecmComfortNoise = Convert.ToInt32(true);

            _voiceDuckLevel = 0.8f;
        }
Example #6
0
        /// <summary>
        ///     Converts a source video to MP4 format.
        /// </summary>
        /// <param name="source">Source video file.</param>
        /// <param name="output">Output video file.</param>
        /// <param name="speed">Conversion speed preset.</param>
        /// <param name="size">Output video size.</param>
        /// <param name="aQuality">Output audio quality.</param>
        /// <param name="multithread">Use multithreading for conversion.</param>
        /// <returns>Success state.</returns>
        public bool ToMp4(VideoInfo source, FileInfo output, Speed speed = Speed.SuperFast,
                          VideoSize size = VideoSize.Original, AudioQuality aQuality = AudioQuality.Normal, bool multithread = false)
        {
            _totalTime = source.Duration;

            FfMpegHelper.ConversionExceptionCheck(source, output);
            FfMpegHelper.ExtensionExceptionCheck(output, FfMpegHelper.Extensions.Mp4);

            var conversionArgs = Arguments.Input(source) +
                                 Arguments.Threads(multithread) +
                                 Arguments.Scale(size) +
                                 Arguments.Video(VideoCodec.LibX264, 2400) +
                                 Arguments.Speed(speed) +
                                 Arguments.Audio(AudioCodec.Aac, aQuality) +
                                 Arguments.Output(output);

            return(RunProcess(conversionArgs, output));
        }
Example #7
0
        /// <summary>
        /// Load defaults into fields, but do not clear prefs
        /// </summary>
        private void LoadDefaults()
        {
            _quality   = AudioQuality.Medium;
            _frameSize = FrameSize.Medium;
            _forwardErrorCorrection = Convert.ToInt32(true);

            _denoiseAmount  = (int)NoiseSuppressionLevels.High;
            _vadSensitivity = (int)VadSensitivityLevels.MediumSensitivity;

            _aecAmount                = (int)AecSuppressionLevels.Disabled;
            _aecDelayAgnostic         = Convert.ToInt32(true);
            _aecExtendedFilter        = Convert.ToInt32(true);
            _aecRefinedAdaptiveFilter = Convert.ToInt32(true);

            _aecmRoutingMode  = (int)AecmRoutingMode.Disabled;
            _aecmComfortNoise = Convert.ToInt32(true);

            _voiceDuckLevel = 0.75f;
        }
Example #8
0
        /// <summary>
        ///     Converts a source video to WebM format.
        /// </summary>
        /// <param name="source">Source video file.</param>
        /// <param name="output">Output video file.</param>
        /// <param name="size">Output video size.</param>
        /// <param name="aQuality">Output audio quality.</param>
        /// <returns>Success state.</returns>
        public bool ToWebM(VideoInfo source, FileInfo output, VideoSize size = VideoSize.Original,
                           AudioQuality aQuality = AudioQuality.Normal)
        {
            _totalTime = source.Duration;

            FfMpegHelper.ConversionExceptionCheck(source, output);
            FfMpegHelper.ExtensionExceptionCheck(output, FfMpegHelper.Extensions.WebM);

            var newHeight = source.Height * (source.Width / (int)size);

            var conversionArgs = Arguments.Input(source) +
                                 Arguments.Scale(size, newHeight) +
                                 Arguments.Video(VideoCodec.LibVpx, 2400) +
                                 Arguments.Speed(16) +
                                 Arguments.Audio(AudioCodec.LibVorbis, aQuality) +
                                 Arguments.Output(output);

            return(RunProcess(conversionArgs, output));
        }
Example #9
0
        public static bool CheckIfQualityIsAvailable(AudioQuality audioQuality, TrackInfo trackInfo)
        {
            switch (audioQuality)
            {
            case AudioQuality.Flac:
                return(trackInfo.TrackTags.Flac != 0);

            case AudioQuality.Mp3320:
                return(trackInfo.TrackTags.Mp3320 != 0);

            case AudioQuality.Mp3256:
                return(trackInfo.TrackTags.Mp3256 != 0);

            case AudioQuality.Mp3128:
                return(trackInfo.TrackTags.Mp3128 != 0);

            default:
                return(false);
            }
        }
Example #10
0
    private void Initialize(string deviceName, AudioQuality quality)
    {
      try
      {
        this.quality = quality;
        this.samplesSize = DefaultBufferSize;

        ALFormat format;

        if (quality.Channels == 1)
          format = quality.Bits == 8 ? ALFormat.Mono8 : ALFormat.Mono16;
        else
          format = quality.Bits == 8 ? ALFormat.Stereo8 : ALFormat.Stereo16;

        lock (syncObj)
        {
          buffer = new byte[quality.Channels * (quality.Bits / 8) * samplesSize * 2];

          if (string.IsNullOrEmpty(deviceName))
            deviceName = AudioCapture.DefaultDevice;

          if (!AudioCapture.AvailableDevices.Contains(deviceName))
            deviceName = AudioCapture.DefaultDevice;

          capture = new AudioCapture(deviceName, quality.Frequency, format, samplesSize * 2);
        }
      }
      catch (Exception e)
      {
        if (capture != null)
          capture.Dispose();

        capture = null;

        ClientModel.Logger.Write(e);
        throw new ModelException(ErrorCode.AudioNotEnabled, "Audio recorder do not initialized.", e, deviceName);
      }
    }
Example #11
0
        private async Task DownloadFromSearch(AudioQuality quality)
        {
            var deezerDownloader = new DeezerDownloader(_deezerHttp, quality);
            var deezerSearcher   = new DeezerSearcher(_deezerHttp);

            string searchType  = Helpers.TakeInput(1, 4, "Track", "Album", "Artist", "Playlist");
            string searchParam = Helpers.TakeInput("Enter search term: ");

            switch (searchType)
            {
            case "1":
                SearchResult trackResult = await deezerSearcher.Search(searchParam, SearchType.Track);

                if (trackResult != null)
                {
                    var e = await deezerDownloader.ProcessTrack(trackResult.Id, trackResult.Json);
                }
                break;

            case "2":
                SearchResult albumId = await deezerSearcher.Search(searchParam, SearchType.Album);

                var i = await deezerDownloader.ProcessAlbum(albumId.Id);

                break;

            case "3":
                SearchResult artistId = await deezerSearcher.Search(searchParam, SearchType.Artist);

                break;

            case "4":
                SearchResult playlistId = await deezerSearcher.Search(searchParam, SearchType.Playlist);

                break;
            }
        }
 public static IConversion ToWebM(string inputPath, string outputPath, VideoSize size = null, AudioQuality audioQuality = AudioQuality.Normal)
 {
     return(new Conversion()
            .SetInput(inputPath)
            .SetScale(size)
            .SetVideo(VideoCodec.LibVpx, 2400)
            .SetSpeed(16)
            .SetAudio(AudioCodec.LibVorbis, audioQuality)
            .SetOutput(outputPath));
 }
 public FFMpegArgumentOptions WithAudioBitrate(AudioQuality audioQuality) => WithArgument(new AudioBitrateArgument(audioQuality));
Example #14
0
        public void SetOptions(string deviceName, AudioQuality quality)
        {
            if (IsInited)
              {
            Stop();
            capture.Dispose();
              }

              Initialize(deviceName, quality);
        }
Example #15
0
 internal static string Audio(AudioCodec codec, AudioQuality bitrate)
 {
     return(Audio(codec) + Audio(bitrate));
 }
Example #16
0
 public AudioBitrateArgument(AudioQuality value) : this((int)value)
 {
 }
Example #17
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);

            _totalTime = source.Duration;

            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;
            }

            var container = new ArgumentContainer();

            switch (type)
            {
            case VideoType.Mp4:
                container.Add(
                    new InputArgument(source),
                    new ThreadsArgument(multithreaded),
                    new ScaleArgument(outputSize),
                    new VideoCodecArgument(VideoCodec.LibX264, 2400),
                    new SpeedArgument(speed),
                    new AudioCodecArgument(AudioCodec.Aac, audioQuality),
                    new OutputArgument(output)
                    );
                break;

            case VideoType.Ogv:
                container.Add(
                    new InputArgument(source),
                    new ThreadsArgument(multithreaded),
                    new ScaleArgument(outputSize),
                    new VideoCodecArgument(VideoCodec.LibTheora, 2400),
                    new SpeedArgument(speed),
                    new AudioCodecArgument(AudioCodec.LibVorbis, audioQuality),
                    new OutputArgument(output)
                    );
                break;

            case VideoType.Ts:
                container.Add(
                    new InputArgument(source),
                    new CopyArgument(),
                    new BitStreamFilterArgument(Channel.Video, Filter.H264_Mp4ToAnnexB),
                    new ForceFormatArgument(VideoCodec.MpegTs),
                    new OutputArgument(output)
                    );
                break;
            }

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

            _totalTime = TimeSpan.MinValue;

            return(new VideoInfo(output));
        }
Example #18
0
        public async Task <bool> ProcessTrack(string id, AlbumInfo albumInfo = null, TrackInfo trackInfo = null)
        {
            var trackProgress = new ProgressBar(100, 100);

            if (trackInfo == null)
            {
                trackInfo = await GetTrackInfo(id);

                if (trackInfo == null)
                {
                    trackProgress.Refresh(0, $"{id} | Failed to get track info");
                    return(false);
                }
            }

            if (albumInfo == null)
            {
                string albumId = trackInfo.TrackTags.AlbumId;

                albumInfo = await GetAlbumInfo(albumId) ?? new AlbumInfo
                {
                    AlbumTags = new AlbumTags
                    {
                        Artists = new [] { new Artists {
                                               Name = "Unknown Artist"
                                           } },
                        Type           = "Unknown",
                        Title          = albumId ?? "Unknown Collection " + Helpers.GetRandomChars(5),
                        NumberOfDiscs  = "0",
                        NumberOfTracks = "0"
                    }
                };
            }

            AudioQuality qualityToUse = FindAvailableAudioQuality(trackInfo);

            if (qualityToUse == AudioQuality.None)
            {
                Helpers.RedMessage("Failed to find any available audio quality");
                return(false);
            }

            string trackProgressTitle =
                $"\nDownloading {albumInfo.AlbumTags.Artists[0].Name} - {trackInfo.TrackTags.Title} | Quality: {DeezerHelpers.AudioQualityToOutputString[qualityToUse]}";

            trackProgress.Next($"{trackProgressTitle} | Getting save location");
            string saveLocation          = DeezerHelpers.BuildSaveLocation(trackInfo, albumInfo, qualityToUse);
            string saveLocationDirectory = Path.GetDirectoryName(saveLocation);
            string tempTrackPath         = DeezerHelpers.GetTempTrackPath(saveLocationDirectory, trackInfo.TrackTags.Id);

            if (File.Exists(saveLocation))
            {
                trackProgress.Refresh(100, $"{trackProgressTitle} | file already exists");
                return(true);
            }

            byte[] decryptedBytes = await GetDecryptedBytes(trackInfo, qualityToUse, trackProgress, trackProgressTitle);

            trackProgress.Next($"{trackProgressTitle} | Writing to disk");
            if (!DeezerHelpers.WriteTrackBytes(decryptedBytes, tempTrackPath))
            {
                trackProgress.Refresh(0, $"{trackProgressTitle} | Failed to write file to disk");
                return(false);
            }

            byte[] albumCover = await GetAndSaveAlbumArt(albumInfo.AlbumTags.PictureId, saveLocationDirectory);

            trackProgress.Next($"{trackProgressTitle} | Writing metadata");
            var metadataWriter = new MetadataWriter(trackInfo, albumInfo, tempTrackPath, albumCover);

            if (!metadataWriter.WriteMetaData(qualityToUse == AudioQuality.Flac))
            {
                trackProgress.Refresh(0, $"{trackProgressTitle} | Failed to write tags");
            }

            DeezerHelpers.RenameFiles(tempTrackPath, saveLocation, saveLocationDirectory);

            trackProgress.Next($"{trackProgressTitle} | Complete");
            return(true);
        }
Example #19
0
 internal static string Audio(AudioQuality bitrate)
 {
     return(Audio((int)bitrate));
 }
Example #20
0
 /// <summary>
 ///     Converts a source video to WebM format.
 /// </summary>
 /// <param name="source">Source video file.</param>
 /// <param name="output">Output video file.</param>
 /// <param name="size">Output video size.</param>
 /// <param name="aQuality">Output audio quality.</param>
 /// <returns>Success state.</returns>
 public static bool ToWebM(this FFMpeg encoder, string source, string output, VideoSize size = VideoSize.Original,
                           AudioQuality aQuality = AudioQuality.Normal)
 {
     return(encoder.ToWebM(VideoInfo.FromPath(source), new FileInfo(output), size, aQuality));
 }
Example #21
0
 /// <summary>
 ///     Converts a source video to OGV format.
 /// </summary>
 /// <param name="source">Source video file.</param>
 /// <param name="output">Output video file.</param>
 /// <param name="size">Output video size.</param>
 /// <param name="aQuality">Output audio quality.</param>
 /// <param name="multithread">Use multithreading for conversion.</param>
 /// <returns>Success state.</returns>
 public static bool ToOgv(this FFMpeg encoder, string source, string output, VideoSize size = VideoSize.Original,
                          AudioQuality aQuality = AudioQuality.Normal, bool multithread = false)
 {
     return(encoder.ToOgv(VideoInfo.FromPath(source), new FileInfo(output), size, aQuality, multithread));
 }
 public AudioCodecArgument(AudioCodec value, AudioQuality bitrate) : base(value)
 {
     Bitrate = (int)bitrate;
 }
Example #23
0
 internal static string Audio(AudioCodec codec, AudioQuality bitrate)
 {
     return($"-codec:a {codec.ToString().ToLower()} -b:a {(int) bitrate}k -strict experimental ");
 }
Example #24
0
 /// <inheritdoc />
 public IConversion SetAudio(AudioCodec codec, AudioQuality bitrate)
 {
     return(SetAudio(codec.ToString(), bitrate));
 }
Example #25
0
 public DeezerDownloader(DeezerHttp deezerHttp, AudioQuality audioQuality)
 {
     _deezerHttp   = deezerHttp;
     _audioQuality = audioQuality;
 }
Example #26
0
 public string GetArgsLine() =>
 $" -c:v { VideoConverter } -preset { Preset.ToString().ToLower() } -crf { CRFScale } -c:a { AudioConverter } -q:a { AudioQuality.ToString("F0") } ";
Example #27
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 static bool Convert(
            string input,
            string output,
            ContainerFormat format,
            Speed speed               = Speed.SuperFast,
            VideoSize size            = VideoSize.Original,
            AudioQuality audioQuality = AudioQuality.Normal,
            bool multithreaded        = false)
        {
            FFMpegHelper.ExtensionExceptionCheck(output, format.Extension);
            var source = FFProbe.Analyse(input);

            FFMpegHelper.ConversionSizeExceptionCheck(source);

            var scale      = VideoSize.Original == size ? 1 : (double)source.PrimaryVideoStream !.Height / (int)size;
            var outputSize = new Size((int)(source.PrimaryVideoStream !.Width / scale), (int)(source.PrimaryVideoStream.Height / scale));

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

            return(format.Name switch
            {
                "mp4" => FFMpegArguments
                .FromFileInput(input)
                .OutputToFile(output, true, options => options
                              .UsingMultithreading(multithreaded)
                              .WithVideoCodec(VideoCodec.LibX264)
                              .WithVideoBitrate(2400)
                              .WithVideoFilters(filterOptions => filterOptions
                                                .Scale(outputSize))
                              .WithSpeedPreset(speed)
                              .WithAudioCodec(AudioCodec.Aac)
                              .WithAudioBitrate(audioQuality))
                .ProcessSynchronously(),
                "ogv" => FFMpegArguments
                .FromFileInput(input)
                .OutputToFile(output, true, options => options
                              .UsingMultithreading(multithreaded)
                              .WithVideoCodec(VideoCodec.LibTheora)
                              .WithVideoBitrate(2400)
                              .WithVideoFilters(filterOptions => filterOptions
                                                .Scale(outputSize))
                              .WithSpeedPreset(speed)
                              .WithAudioCodec(AudioCodec.LibVorbis)
                              .WithAudioBitrate(audioQuality))
                .ProcessSynchronously(),
                "mpegts" => FFMpegArguments
                .FromFileInput(input)
                .OutputToFile(output, true, options => options
                              .CopyChannel()
                              .WithBitStreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB)
                              .ForceFormat(VideoType.Ts))
                .ProcessSynchronously(),
                "webm" => FFMpegArguments
                .FromFileInput(input)
                .OutputToFile(output, true, options => options
                              .UsingMultithreading(multithreaded)
                              .WithVideoCodec(VideoCodec.LibVpx)
                              .WithVideoBitrate(2400)
                              .WithVideoFilters(filterOptions => filterOptions
                                                .Scale(outputSize))
                              .WithSpeedPreset(speed)
                              .WithAudioCodec(AudioCodec.LibVorbis)
                              .WithAudioBitrate(audioQuality))
                .ProcessSynchronously(),
                _ => throw new ArgumentOutOfRangeException(nameof(format))
            });
Example #28
0
        public static string BuildSaveLocation(TrackInfo trackInfo, AlbumInfo albumInfo, AudioQuality audioQuality)
        {
            string artist      = albumInfo.AlbumTags.Artists[0].Name.SanitseString();
            string type        = albumInfo.AlbumTags.Type.SanitseString();
            string albumTitle  = albumInfo.AlbumTags.Title.SanitseString();
            string trackTitle  = trackInfo.TrackTags.Title.SanitseString();
            string discNumber  = trackInfo.TrackTags.DiscNumber.SanitseString();
            string trackNumber = trackInfo.TrackTags.TrackNumber.SanitseString().PadNumber();
            string totalDiscs  = albumInfo.AlbumTags.NumberOfDiscs ?? "1";

            var    downloadPath = Configuration.GetValue <string>("downloadLocation");
            string extension    = audioQuality == AudioQuality.Flac
                ? ".flac"
                : ".mp3";

            string filename      = $"{trackNumber} - {trackTitle}{extension}";
            string directoryPath = $@"{artist}\{albumTitle} ({type})\";

            if (int.Parse(totalDiscs) > 1)
            {
                directoryPath += $@"Disc {discNumber}\";
            }

            string savePath = Path.Combine(downloadPath, directoryPath, filename);

            return(savePath);
        }
Example #29
0
 /// <inheritdoc />
 public IConversion SetAudio(string codec, AudioQuality bitrate)
 {
     _audio = $"-codec:a {codec.ToLower()} -b:a {(int) bitrate}k -strict experimental ";
     return(this);
 }
Example #30
0
 public VoiceService(string yandexUrl, string yandexApiKey, string defaultLanguage, AudioFormat format, AudioQuality quality)
 {
     Format           = format;
     _defaultLanguage = defaultLanguage;
     _voiceGenerator  = new VoiceGenerator(yandexUrl, yandexApiKey, format, quality);
 }
Example #31
0
 /// <summary>
 ///     Convert file to OGV
 /// </summary>
 /// <param name="inputPath">Input path</param>
 /// <param name="outputPath">Destination file</param>
 /// <param name="size">Dimension</param>
 /// <param name="audioQuality">Audio quality</param>
 /// <param name="multithread">Use multithread</param>
 /// <returns>Conversion result</returns>
 public static IConversion ToOgv(string inputPath, string outputPath, VideoSize size = null, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false)
 {
     return(new Conversion()
            .SetInput(inputPath)
            .SetScale(size)
            .SetVideo(VideoCodec.LibTheora, 2400)
            .SetAudio(AudioCodec.LibVorbis, audioQuality)
            .SetOutput(outputPath)
            .UseMultiThread(multithread));
 }
Example #32
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 = ArgumentsStringifier.Input(source) +
                       ArgumentsStringifier.Threads(multithreaded) +
                       ArgumentsStringifier.Scale(outputSize) +
                       ArgumentsStringifier.Video(VideoCodec.LibX264, 2400) +
                       ArgumentsStringifier.Speed(speed) +
                       ArgumentsStringifier.Audio(AudioCodec.Aac, audioQuality) +
                       ArgumentsStringifier.Output(output);
                break;

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

                break;

            case VideoType.Ts:
                args = ArgumentsStringifier.Input(source) +
                       ArgumentsStringifier.Copy() +
                       ArgumentsStringifier.BitStreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB) +
                       ArgumentsStringifier.ForceFormat(VideoCodec.MpegTs) +
                       ArgumentsStringifier.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));
        }