/// <summary>
 /// Convert WAV to AAC
 /// </summary>
 /// <param name="waveFileName"></param>
 /// <param name="mp3FileName"></param>
 /// <param name="bitRate"></param>
 public void WaveToAAC(string waveFileName, string aacFileName, int bitRate = 44100)
 {
     using (MediaFoundationReader reader = new MediaFoundationReader(waveFileName))
     {
         NAudio.MediaFoundation.MediaType mt = new NAudio.MediaFoundation.MediaType();
         mt.MajorType = NAudio.MediaFoundation.MediaTypes.MFMediaType_Audio;
         mt.SubType = NAudio.MediaFoundation.AudioSubtypes.MFAudioFormat_AAC;
         mt.BitsPerSample = 16;
         mt.SampleRate = bitRate;
         mt.ChannelCount = 2;
         using (MediaFoundationEncoder mfe = new MediaFoundationEncoder(mt))
         {
             mfe.Encode(aacFileName, reader);
         }
         //MediaFoundationEncoder.EncodeToAac(reader, aacFileName, bitRate);
     }
 }
        public override void ProcessItem(IJob job, IJobItem item)
        {
            var bitRate = job.Preset.BitRate;
            var sampleRate = job.Preset.SampleRate;
            var tempdir = Path.GetTempPath();
            var tempfile = Path.Combine(tempdir, DateTime.Now.Ticks + "." + job.Preset.Extension);

            var subType = this.GetAudioSubtypeForExtension(job.Preset.Extension);
            var waveFormat = new WaveFormat(sampleRate, 2);

            var mediaType = MediaFoundationEncoder.SelectMediaType(subType, waveFormat, bitRate);

            if (mediaType != null)
            {
                using (var decoder = new MediaFoundationReader(item.LastFile))
                {
                    using (var encoder = new MediaFoundationEncoder(mediaType))
                    {
                        encoder.Encode(tempfile, decoder);
                    }
                }
            }

            item.TemporaryFiles.Add(tempfile);
        }
Esempio n. 3
0
        // Token: 0x06000945 RID: 2373 RVA: 0x0001B0A0 File Offset: 0x000192A0
        private long ConvertOneBuffer(IMFSinkWriter writer, int streamIndex, IWaveProvider inputProvider, long position, byte[] managedBuffer)
        {
            long           num            = 0L;
            IMFMediaBuffer imfmediaBuffer = MediaFoundationApi.CreateMemoryBuffer(managedBuffer.Length);
            int            count;

            imfmediaBuffer.GetMaxLength(out count);
            IMFSample imfsample = MediaFoundationApi.CreateSample();

            imfsample.AddBuffer(imfmediaBuffer);
            IntPtr destination;
            int    num2;

            imfmediaBuffer.Lock(out destination, out count, out num2);
            int num3 = inputProvider.Read(managedBuffer, 0, count);

            if (num3 > 0)
            {
                num = MediaFoundationEncoder.BytesToNsPosition(num3, inputProvider.WaveFormat);
                Marshal.Copy(managedBuffer, 0, destination, num3);
                imfmediaBuffer.SetCurrentLength(num3);
                imfmediaBuffer.Unlock();
                imfsample.SetSampleTime(position);
                imfsample.SetSampleDuration(num);
                writer.WriteSample(streamIndex, imfsample);
            }
            else
            {
                imfmediaBuffer.Unlock();
            }
            Marshal.ReleaseComObject(imfsample);
            Marshal.ReleaseComObject(imfmediaBuffer);
            return(num);
        }
 /// <summary>
 /// Helper function to simplify encoding to MP3
 /// By default, will only be available on Windows 8 and above
 /// </summary>
 /// <param name="inputProvider">Input provider, must be PCM</param>
 /// <param name="outputFile">Output file path, should end with .mp3</param>
 /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
 public static void EncodeToMp3(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);
     using (var encoder = new MediaFoundationEncoder(mediaType))
     {
         encoder.Encode(outputFile, inputProvider);
     }
 }
Esempio n. 5
0
 /// <summary>
 /// Queries the available bitrates for a given encoding output type, sample rate and number of channels
 /// </summary>
 /// <param name="audioSubtype">Audio subtype - a value from the AudioSubtypes class</param>
 /// <param name="sampleRate">The sample rate of the PCM to encode</param>
 /// <param name="channels">The number of channels of the PCM to encode</param>
 /// <returns>An array of available bitrates in average bits per second</returns>
 // Token: 0x0600093A RID: 2362 RVA: 0x0001AAE0 File Offset: 0x00018CE0
 public static int[] GetEncodeBitrates(Guid audioSubtype, int sampleRate, int channels)
 {
     return((from br in (from mt in MediaFoundationEncoder.GetOutputMediaTypes(audioSubtype)
                         where mt.SampleRate == sampleRate && mt.ChannelCount == channels
                         select mt.AverageBytesPerSecond * 8).Distinct <int>()
             orderby br
             select br).ToArray <int>());
 }
        /// <summary>
        /// Helper function to simplify encoding to MP3
        /// By default, will only be available on Windows 8 and above
        /// </summary>
        /// <param name="inputProvider">Input provider, must be PCM</param>
        /// <param name="outputFile">Output file path, should end with .mp3</param>
        /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
        public static void EncodeToMp3(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
        {
            var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);

            using (var encoder = new MediaFoundationEncoder(mediaType))
            {
                encoder.Encode(outputFile, inputProvider);
            }
        }
Esempio n. 7
0
 /// <summary>
 /// Helper function to simplify encoding to MP3
 /// By default, will only be available on Windows 8 and above
 /// </summary>
 /// <param name="inputProvider">Input provider, must be PCM</param>
 /// <param name="outputFile">Output file path, should end with .mp3</param>
 /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
 public static void EncodeToMp3(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_MP3, inputProvider.WaveFormat, desiredBitRate);
     if (mediaType == null) throw new InvalidOperationException("No suitable MP3 encoders available");
     using (var encoder = new MediaFoundationEncoder(mediaType))
     {
         encoder.Encode(outputFile, inputProvider);
     }
 }
 /// <summary>
 /// Helper function to simplify encoding to AAC
 /// By default, will only be available on Windows 7 and above
 /// </summary>
 /// <param name="inputProvider">Input provider, must be PCM</param>
 /// <param name="outputFile">Output file path, should end with .mp4 (or .aac on Windows 8)</param>
 /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
 public static void EncodeToAac(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     // Information on configuring an AAC media type can be found here:
     // http://msdn.microsoft.com/en-gb/library/windows/desktop/dd742785%28v=vs.85%29.aspx
     var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_AAC, inputProvider.WaveFormat, desiredBitRate);
     using (var encoder = new MediaFoundationEncoder(mediaType))
     {
         // should AAC container have ADTS, or is that just for ADTS?
         // http://www.hydrogenaudio.org/forums/index.php?showtopic=97442
         encoder.Encode(outputFile, inputProvider);
     }
 }
Esempio n. 9
0
 /// <summary>
 /// Tries to find the encoding media type with the closest bitrate to that specified
 /// </summary>
 /// <param name="audioSubtype">Audio subtype, a value from AudioSubtypes</param>
 /// <param name="inputFormat">Your encoder input format (used to check sample rate and channel count)</param>
 /// <param name="desiredBitRate">Your desired bitrate</param>
 /// <returns>The closest media type, or null if none available</returns>
 // Token: 0x0600093F RID: 2367 RVA: 0x0001AE7C File Offset: 0x0001907C
 public static MediaType SelectMediaType(Guid audioSubtype, WaveFormat inputFormat, int desiredBitRate)
 {
     return((from mt in MediaFoundationEncoder.GetOutputMediaTypes(audioSubtype)
             where mt.SampleRate == inputFormat.SampleRate && mt.ChannelCount == inputFormat.Channels
             select new
     {
         MediaType = mt,
         Delta = Math.Abs(desiredBitRate - mt.AverageBytesPerSecond * 8)
     } into mt
             orderby mt.Delta
             select mt.MediaType).FirstOrDefault <MediaType>());
 }
Esempio n. 10
0
 public static void EncodeToWma(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
 {
     MediaType mediaType = MediaFoundationEncoder.SelectMediaType(AudioSubtypes.MFAudioFormat_WMAudioV8, inputProvider.WaveFormat, desiredBitRate);
     if (mediaType == null)
     {
         throw new InvalidOperationException("No suitable WMA encoders available");
     }
     using (MediaFoundationEncoder mediaFoundationEncoder = new MediaFoundationEncoder(mediaType))
     {
         mediaFoundationEncoder.Encode(outputFile, inputProvider);
     }
 }
        /// <summary>
        /// Helper function to simplify encoding to AAC
        /// By default, will only be available on Windows 7 and above
        /// </summary>
        /// <param name="inputProvider">Input provider, must be PCM</param>
        /// <param name="outputFile">Output file path, should end with .mp4 (or .aac on Windows 8)</param>
        /// <param name="desiredBitRate">Desired bitrate. Use GetEncodeBitrates to find the possibilities for your input type</param>
        public static void EncodeToAac(IWaveProvider inputProvider, string outputFile, int desiredBitRate = 192000)
        {
            // Information on configuring an AAC media type can be found here:
            // http://msdn.microsoft.com/en-gb/library/windows/desktop/dd742785%28v=vs.85%29.aspx
            var mediaType = SelectMediaType(AudioSubtypes.MFAudioFormat_AAC, inputProvider.WaveFormat, desiredBitRate);

            using (var encoder = new MediaFoundationEncoder(mediaType))
            {
                // should AAC container have ADTS, or is that just for ADTS?
                // http://www.hydrogenaudio.org/forums/index.php?showtopic=97442
                encoder.Encode(outputFile, inputProvider);
            }
        }
Esempio n. 12
0
 public void Encode(string outputFile, IWaveProvider inputProvider)
 {
     if (inputProvider.WaveFormat.Encoding != WaveFormatEncoding.Pcm && inputProvider.WaveFormat.Encoding != WaveFormatEncoding.IeeeFloat)
     {
         throw new ArgumentException("Encode input format must be PCM or IEEE float");
     }
     MediaType mediaType = new MediaType(inputProvider.WaveFormat);
     IMFSinkWriter imfsinkWriter = MediaFoundationEncoder.CreateSinkWriter(outputFile);
     try
     {
         int num;
         imfsinkWriter.AddStream(this.outputMediaType.MediaFoundationObject, out num);
         imfsinkWriter.SetInputMediaType(num, mediaType.MediaFoundationObject, null);
         this.PerformEncode(imfsinkWriter, num, inputProvider);
     }
     finally
     {
         Marshal.ReleaseComObject(imfsinkWriter);
         Marshal.ReleaseComObject(mediaType.MediaFoundationObject);
     }
 }
Esempio n. 13
0
 private void Encode()
 {
     using (var reader = new MediaFoundationReader(_fileLocation))
     {
         var SelectedOutputFormat = new Encoder()
         {
             Name = "MP3",
             Guid = AudioSubtypes.MFAudioFormat_MP3,
             Extension = ".mp3"
         };
         var list = MediaFoundationEncoder.GetOutputMediaTypes(SelectedOutputFormat.Guid)
                           .Select(mf => new MediaTypeUtils(mf))
                           .ToList();
         string outputUrl = SelectSaveFile();
         if (outputUrl == null) return;
         using (var encoder = new MediaFoundationEncoder(list[0].MediaType))
         {
             encoder.Encode(outputUrl, reader);
         }
     }
 }
        private void Encode()
        {
            if (String.IsNullOrEmpty(InputFile)||!File.Exists(InputFile))
            {
                MessageBox.Show("Please select a valid input file to convert");
                return;
            }
            if (SelectedMediaType == null || SelectedMediaType.MediaType == null)
            {
                MessageBox.Show("Please select a valid output format");
                return;
            }

            using (var reader = new MediaFoundationReader(InputFile))
            {
                string outputUrl = SelectSaveFile(SelectedOutputFormat.Name, SelectedOutputFormat.Extension);
                if (outputUrl == null) return;
                using (var encoder = new MediaFoundationEncoder(SelectedMediaType.MediaType))
                {
                    encoder.Encode(outputUrl, reader);
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Transcodes the source audio to the target format and quality.
        /// </summary>
        /// <param name="formatType">Format to convert this audio to.</param>
        /// <param name="quality">Quality of the processed output audio. For streaming formats, it can be one of the following: Low (96 kbps), Medium (128 kbps), Best (192 kbps).  For WAV formats, it can be one of the following: Low (11kHz ADPCM), Medium (22kHz ADPCM), Best (44kHz PCM)</param>
        /// <param name="targetFileName">Name of the file containing the processed source audio. Must be null for Wav and Adpcm. Must not be null for streaming compressed formats.</param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string targetFileName)
        {
            if (disposed)
                throw new ObjectDisposedException("AudioContent");


        switch (formatType)
            {
                case ConversionFormat.Adpcm:
#if WINDOWS
                    ConvertWav(new AdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                    break;
#else
                    throw new NotSupportedException("Adpcm encoding supported on Windows only");
#endif

                case ConversionFormat.Pcm:
#if WINDOWS
                    ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                    break;
#elif LINUX
                    // TODO Do the conversion for Linux platform
                    throw new NotSupportedException("Pcm has not been implemented on this platform");
#else //MONOMAC
                    targetFileName = Guid.NewGuid().ToString() + ".wav";
                    if (!ConvertAudio.Convert(fileName, targetFileName, AudioFormatType.LinearPCM, MonoMac.AudioToolbox.AudioFileType.WAVE, quality)) {
                        throw new InvalidDataException("Failed to convert to PCM");
                    }
                    Read(targetFileName);
                    if (File.Exists(targetFileName))
                        File.Delete(targetFileName);
                    break;
#endif

                case ConversionFormat.WindowsMedia:
#if WINDOWS
                    reader.Position = 0;
                    MediaFoundationEncoder.EncodeToWma(reader, targetFileName, QualityToBitRate(quality));
                    break;
#else
                    throw new NotSupportedException("WindowsMedia encoding supported on Windows only");
#endif

                case ConversionFormat.Xma:
                    throw new NotSupportedException("XMA is not a supported encoding format. It is specific to the Xbox 360.");

                case ConversionFormat.ImaAdpcm:
#if WINDOWS
                    ConvertWav(new ImaAdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount, 4));
                    break;
#else
                    throw new NotImplementedException("ImaAdpcm has not been implemented on this platform");
#endif

                case ConversionFormat.Aac:
#if WINDOWS
                    reader.Position = 0;
                    var mediaType = SelectMediaType (AudioSubtypes.MFAudioFormat_AAC, reader.WaveFormat, QualityToBitRate (quality));
                    if (mediaType == null) {
                        throw new InvalidDataException ("Cound not find a suitable mediaType to convert to.");
                    }
                    using (var encoder = new MediaFoundationEncoder (mediaType)) {
                        encoder.Encode (targetFileName, reader);
                    }
                    break;
#elif LINUX
                    // TODO: Code for Linux convertion
                    throw new NotImplementedException("Aac has not been implemented on this platform");
#else //MONOMAC
                    if (!ConvertAudio.Convert(fileName, targetFileName, AudioFormatType.MPEG4AAC, MonoMac.AudioToolbox.AudioFileType.MPEG4, quality)) {
                        throw new InvalidDataException("Failed to convert to AAC");
                    }
                    break;
#endif

                case ConversionFormat.Vorbis:
                    throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
        /// <summary>
        /// Creates an MP3-file from the downloaded video file
        /// </summary>
        /// <param name="bytesPerSecond">Audio bitrate in bytes per second</param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        private void PerformConversion(int bytesPerSecond, string input, string output)
        {
            var allMediaTypes = new Dictionary<Guid, List<MediaType>>();
            var list = MediaFoundationEncoder.GetOutputMediaTypes(AudioSubtypes.MFAudioFormat_MP3).ToList();
            allMediaTypes[AudioSubtypes.MFAudioFormat_MP3] = list;

            // Keep audio properties from the original video file
            var supportedMediaTypes = allMediaTypes[AudioSubtypes.MFAudioFormat_MP3]
                .Where(m => m != null)
                .Where(m => m.SampleRate == inputWaveFormat.SampleRate)
                .Where(m => m.ChannelCount == inputWaveFormat.Channels)
                .ToList();

            var mediaType = supportedMediaTypes.FirstOrDefault(m => m.AverageBytesPerSecond == bytesPerSecond) ??
                            supportedMediaTypes.FirstOrDefault();

            if (mediaType != null)
            {
                using (var reader = new MediaFoundationReader(input))
                {
                    using (var encoder = new MediaFoundationEncoder(mediaType))
                    {
                        encoder.Encode(output, reader);
                    }
                }
            }

            // Cleanup before throwing cancellation 
            if (tokenSource.IsCancellationRequested)
            {
                File.Delete(output);
                File.Delete(input);
                tokenSource.Token.ThrowIfCancellationRequested();
            }

            UpdateWorkStatus(WorkStatus.Finished);
        }