Ejemplo n.º 1
0
        private void ConvertClicked(object sender, RoutedEventArgs e)
        {
            if (this.selectedFileName == null)
            {
                MessageBox.Show("You must specify a file first.");
                return;
            }
            if (videoFormatCombo.SelectedValue == null)
            {
                MessageBox.Show("You must select a format first.");
                return;
            }
            ConversionFormat selectedFormat =
                (ConversionFormat)videoFormatCombo.SelectedValue;

            Settings.Default.LastFormatDisplayName =
                selectedFormat.DisplayName;
            Settings.Default.Save();
            if (FileSelected != null)
            {
                FileSelected(this, new VideoSelectedEventArgs(
                                 selectedFileName,
                                 selectedFormat,
                                 (sendToITunes.IsChecked.HasValue &&
                                  sendToITunes.IsChecked.Value)));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Transcodes the source audio to the target format and quality.
        /// </summary>
        /// <param name="formatType">Format of the processed source audio: WAV, MP3 or WMA.</param>
        /// <param name="quality">Quality of the processed source audio. It can be one of the following: Low (96 kbps), Medium (128 kbps), Best (192 kbps)</param>
        /// <param name="targetFileName">Name of the file containing the processed source audio.</param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string targetFileName)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("AudioContent");
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 3
0
        private void videoFormatCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ConversionFormat selectedValue =
                (ConversionFormat)videoFormatCombo.SelectedValue;

            sendToITunes.Visibility =
                (selectedValue.Group == VideoFormatGroup.Apple ?
                 Visibility.Visible : Visibility.Hidden);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes an instance of <see cref="ConversionRequest"/>.
 /// </summary>
 public ConversionRequest(
     string ffmpegCliFilePath,
     string outputFilePath,
     ConversionFormat format,
     ConversionPreset preset)
 {
     FFmpegCliFilePath = ffmpegCliFilePath;
     OutputFilePath    = outputFilePath;
     Format            = format;
     Preset            = preset;
 }
Ejemplo n.º 5
0
        private void ShowConvertingView(string fileName, ConversionFormat format, bool sendToITunesSelected)
        {
            Converting convertingView = new Converting(fileName, format, sendToITunesSelected);

            this.mainGrid.Children.Add(convertingView);
            convertingView.Margin = new Thickness(0);
            convertingView.HorizontalAlignment = HorizontalAlignment.Stretch;
            convertingView.VerticalAlignment   = VerticalAlignment.Stretch;
            convertingView.Finished           += new EventHandler <VideoConvertFinishedArgs>(convertingView_Finished);
            convertingView.Cancelled          += new EventHandler <EventArgs>(convertingView_Cancelled);
            convertingView.UnknownFormat      += new EventHandler <EventArgs>(convertingView_UnknownFormat);
        }
Ejemplo n.º 6
0
        private IntPtr DdeClientCallback(int uType, ConversionFormat uFmt, IntPtr hConv, IntPtr hsz1, IntPtr hsz2, IntPtr hData, uint dwData1, uint dwData2)
        {
            int dwLength = 0;

            //DateTime time = DateTime.Now;
            unsafe
            {
                switch (uType)
                {
                case Ddeml.XTYP_ADVDATA:
                    try
                    {
                        sbyte *pData = (sbyte *)Ddeml.DdeAccessData(hData, ref dwLength);
                        if (pData != null)
                        {
                            sbyte *pSZ = stackalloc sbyte[0xFF];
                            Ddeml.DdeQueryString(dwDDEInst, hsz2, pSZ, 0xFF, Ddeml.CP_WINANSI);
                            if (DDEValueChange != null)
                            {
                                DDEValueChange(this, new DDEValueChangeEventArgs(new string(pSZ).ToUpper(), new string(pData, 0, dwLength)));
                            }
                        }
                    }
                    catch { }
                    finally
                    {
                        if (hData != IntPtr.Zero)
                        {
                            Ddeml.DdeUnaccessData(hData);
                        }
                    }
                    break;

                case Ddeml.XTYP_DISCONNECT:
                    if (OnError != null)
                    {
                        OnError(this, new IOErrorEventArgs("XTYP_DISCONNECT"));
                    }
                    _connected = false;
                    break;

                case Ddeml.XTYP_XACT_COMPLETE:
                    break;

                default:
                    break;
                }
            }
            return(new IntPtr(Ddeml.DDE_FACK));
        }
Ejemplo n.º 7
0
 internal Converting(string fileName, ConversionFormat format, bool sendToITunesSelected)
 {
     InitializeComponent();
     this.conversionFormat     = format;
     this.sendToITunesSelected = sendToITunesSelected;
     this.ffmpegOutput         = new List <string>();
     fileNameLabel.Content     = IOPath.GetFileName(fileName);
     progressLabel.Content     = "Starting...";
     converter                  = format.MakeConverter(fileName);
     converter.Output          += new EventHandler <ProcessOutputArgs>(converter_FFMPEGOutput);
     converter.ConvertProgress +=
         new EventHandler <VideoConvertProgressArgs>(converter_ConvertProgress);
     converter.Finished      += new EventHandler <EventArgs>(converter_Finished);
     converter.UnknownFormat += new EventHandler <EventArgs>(converter_UnknownFormat);
     converter.Start();
 }
Ejemplo n.º 8
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:
                ConvertWav(new AdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                break;

            case ConversionFormat.Pcm:
                ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                break;

            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:
                ConvertWav(new ImaAdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount, 4));
                break;

            case ConversionFormat.Aac:
#if WINDOWS
                reader.Position = 0;
                MediaFoundationEncoder.EncodeToAac(reader, targetFileName, QualityToBitRate(quality));
                break;
#else
                throw new NotImplementedException();
#endif

            case ConversionFormat.Vorbis:
                throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
Ejemplo n.º 9
0
        private void WasLoaded(object sender, RoutedEventArgs e)
        {
            ConversionFormat format =
                ConversionFormat.FindByDisplayName(
                    Settings.Default.LastFormatDisplayName);

            if (format == null)
            {
                format = TheoraVideoFormat.Theora;
            }
            videoFormatCombo.SelectedValue = format;
            if (FinishedFileName != null)
            {
                topLabel.Visibility     = Visibility.Hidden;
                finishedGrid.Visibility = Visibility.Visible;
                finishedTextBlock.Text  = string.Format("Finished converting {0}",
                                                        IOPath.GetFileName(FinishedFileName));
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Конвертирует массив данных в нужнный формат с учетом нужной локализации
 /// </summary>
 /// <param name="inputData">Входные данные</param>
 /// <param name="outputFilePath">Файл, в который нужно сохранить данные</param>
 /// <param name="format">Формат файла, в который нужно сохранить</param>
 /// <param name="localisation">Выбранная локализация</param>
 /// <returns>Успех конвертации</returns>
 public static bool convert(System.Data.DataTable inputData, string outputFilePath, ConversionFormat format, Localisation localisation)
 {
     if (format == ConversionFormat.CSV)
     {
         var conv = new CSVConverter();
         return conv.Import(inputData) && conv.Export(outputFilePath, localisation);
     }
     else if (format == ConversionFormat.XLSX)
     {
         var conv = new XLSXConverter();
         return conv.Import(inputData) && conv.Export(outputFilePath, localisation);
     }
     else if (format == ConversionFormat.ARFF)
     {
         var conv = new ARFFConverter();
         return conv.Import(inputData) && conv.Export(outputFilePath, localisation);
     }
     return false;
 }
        private static int ToWavFormat(ConversionFormat format, int bitsPerSample)
        {
            switch (format)
            {
            case ConversionFormat.Pcm:
                if (bitsPerSample == 32)
                {
                    return(3);
                }
                return(1);

            case ConversionFormat.Adpcm:
                return(2);

            case ConversionFormat.WindowsMedia:
            case ConversionFormat.Xma:
            default:
                throw new ArgumentOutOfRangeException("format");
            }
        }
        public void ConvertAudio(string sourceFile, ConversionFormat format, ConversionQuality quality, int channels, int averageBytesPerSecond, int sampleRate, int bitsPerSample, int blockAlign)
        {
            var content = new AudioContent(sourceFile, AudioFileType.Wav);

            content.ConvertFormat(format, quality, null);

            Assert.AreEqual(ToWavFormat(format, content.Format.BitsPerSample), content.Format.Format);
            Assert.AreEqual(channels, content.Format.ChannelCount);
            Assert.AreEqual(bitsPerSample, content.Format.BitsPerSample);

            // TODO: We don't quite match right with XNA on these.
            // We should look to fix this for 100% compatibility.
            if (format != ConversionFormat.Adpcm)
            {
                Assert.AreEqual(sampleRate, content.Format.SampleRate);
                Assert.AreEqual(averageBytesPerSecond, content.Format.AverageBytesPerSecond);
                Assert.AreEqual(blockAlign, content.Format.BlockAlign);
            }

            content.Dispose();
        }
Ejemplo n.º 13
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));
#else
                throw new NotSupportedException("Adpcm encoding supported on Windows only");
#endif
                break;

            case ConversionFormat.Pcm:
#if WINDOWS
                ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
#elif LINUX
                // TODO Do the conversion for Linux platform
#else
                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);
                }
#endif
                break;

            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));
#else
                throw new NotImplementedException("ImaAdpcm has not been implemented on this platform");
#endif
                break;

            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);
                }
#elif LINUX
                // TODO: Code for Linux convertion
#else
                if (!ConvertAudio.Convert(fileName, targetFileName, AudioFormatType.MPEG4AAC, MonoMac.AudioToolbox.AudioFileType.MPEG4, quality))
                {
                    throw new InvalidDataException("Failed to convert to AAC");
                }
#endif
                break;

            case ConversionFormat.Vorbis:
                throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Transcodes the source audio to the target format and quality.
        /// </summary>
        /// <param name="formatType">Format of the processed source audio: WAV, MP3 or WMA.</param>
        /// <param name="quality">Quality of the processed source audio. It can be one of the following: Low (96 kbps), Medium (128 kbps), Best (192 kbps)</param>
        /// <param name="targetFileName">Name of the file containing the processed source audio.</param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string targetFileName)
        {
            if (disposed)
                throw new ObjectDisposedException("AudioContent");

            throw new NotImplementedException();
        }
Ejemplo n.º 15
0
 public static extern IntPtr DdeCreateDataHandle(int idInst, byte[] pSrc, int cb, int cbOff, IntPtr hszItem, ConversionFormat wFmt, int afCmd);
Ejemplo n.º 16
0
 /// <summary>
 /// Gets the file extension for an audio format.
 /// </summary>
 /// <param name="format">The conversion format</param>
 /// <returns>The file extension for the given conversion format.</returns>
 static public string GetExtension(ConversionFormat format)
 {
     return conversionFormatExtensions[(int)format];
 }
Ejemplo n.º 17
0
 public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string targetFileName)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 18
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:
                    ConvertWav(new AdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                    break;

                case ConversionFormat.Pcm:
                    ConvertWav(new WaveFormat(QualityToSampleRate(quality), format.ChannelCount));
                    break;

                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:
                    ConvertWav(new ImaAdpcmWaveFormat(QualityToSampleRate(quality), format.ChannelCount, 4));
                    break;

                case ConversionFormat.Aac:
#if WINDOWS
                    reader.Position = 0;
                    MediaFoundationEncoder.EncodeToAac(reader, targetFileName, QualityToBitRate(quality));
                    break;
#else
                    throw new NotImplementedException();
#endif

                case ConversionFormat.Vorbis:
                    throw new NotImplementedException("Vorbis is not yet implemented as an encoding format.");
            }
        }
Ejemplo n.º 19
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="saveToFile">
        /// The name of the file that the converted audio should be saved into.  This is used for SongContent, where
        /// the audio is stored external to the XNB file.  If this is null, then the converted audio is stored in
        /// the Data property.
        /// </param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string saveToFile)
        {
            if (disposed)
            {
                throw new ObjectDisposedException("AudioContent");
            }

            var temporarySource = Path.GetTempFileName();
            var temporaryOutput = Path.GetTempFileName();

            try
            {
                using (var fs = new FileStream(temporarySource, FileMode.Create, FileAccess.Write))
                {
                    var dataBytes = this.data.ToArray();
                    fs.Write(dataBytes, 0, dataBytes.Length);
                }

                string ffmpegCodecName, ffmpegMuxerName;
                int    format;
                switch (formatType)
                {
                case ConversionFormat.Adpcm:
                    // ADPCM Microsoft
                    ffmpegCodecName = "adpcm_ms";
                    ffmpegMuxerName = "wav";
                    format          = 0x0002; /* WAVE_FORMAT_ADPCM */
                    break;

                case ConversionFormat.Pcm:
                    // PCM signed 16-bit little-endian
                    ffmpegCodecName = "pcm_s16le";
                    ffmpegMuxerName = "s16le";
                    format          = 0x0001; /* WAVE_FORMAT_PCM */
                    break;

                case ConversionFormat.WindowsMedia:
                    // Windows Media Audio 2
                    ffmpegCodecName = "wmav2";
                    ffmpegMuxerName = "asf";
                    format          = 0x0161; /* WAVE_FORMAT_WMAUDIO2 */
                    break;

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

                case ConversionFormat.ImaAdpcm:
                    // ADPCM IMA WAV
                    ffmpegCodecName = "adpcm_ima_wav";
                    ffmpegMuxerName = "wav";
                    format          = 0x0011; /* WAVE_FORMAT_IMA_ADPCM */
                    break;

                case ConversionFormat.Aac:
                    // AAC (Advanced Audio Coding)
                    // Requires -strict experimental
                    ffmpegCodecName = "aac";
                    ffmpegMuxerName = "ipod";
                    format          = 0x0000; /* WAVE_FORMAT_UNKNOWN */
                    break;

                case ConversionFormat.Vorbis:
                    // Vorbis
                    ffmpegCodecName = "libvorbis";
                    ffmpegMuxerName = "ogg";
                    format          = 0x0000; /* WAVE_FORMAT_UNKNOWN */
                    break;

                default:
                    // Unknown format
                    throw new NotSupportedException();
                }

                string ffmpegStdout, ffmpegStderr;
                var    ffmpegExitCode = ExternalTool.Run(
                    "ffmpeg",
                    string.Format(
                        "-y -i \"{0}\" -vn -c:a {1} -b:a {2} -f:a {3} -strict experimental \"{4}\"",
                        temporarySource,
                        ffmpegCodecName,
                        QualityToBitRate(quality),
                        ffmpegMuxerName,
                        temporaryOutput),
                    out ffmpegStdout,
                    out ffmpegStderr);
                if (ffmpegExitCode != 0)
                {
                    throw new InvalidOperationException("ffmpeg exited with non-zero exit code: \n" + ffmpegStdout + "\n" + ffmpegStderr);
                }

                byte[] rawData;
                using (var fs = new FileStream(temporaryOutput, FileMode.Open, FileAccess.Read))
                {
                    rawData = new byte[fs.Length];
                    fs.Read(rawData, 0, rawData.Length);
                }

                if (saveToFile != null)
                {
                    using (var fs = new FileStream(saveToFile, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(rawData, 0, rawData.Length);
                    }

                    this.data = null;
                }
                else
                {
                    this.data = rawData.ToList();
                }

                string ffprobeStdout, ffprobeStderr;
                var    ffprobeExitCode = ExternalTool.Run(
                    "ffprobe",
                    string.Format("-i \"{0}\" -show_entries streams -v quiet -of flat", temporarySource),
                    out ffprobeStdout,
                    out ffprobeStderr);
                if (ffprobeExitCode != 0)
                {
                    throw new InvalidOperationException("ffprobe exited with non-zero exit code.");
                }

                // Set default values if information is not available.
                int    averageBytesPerSecond = 0;
                int    bitsPerSample         = 0;
                int    blockAlign            = 0;
                int    channelCount          = 0;
                int    sampleRate            = 0;
                double durationInSeconds     = 0;

                var numberFormat = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
                foreach (var line in ffprobeStdout.Split(new[] { '\r', '\n', '\0' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var kv = line.Split(new[] { '=' }, 2);

                    switch (kv[0])
                    {
                    case "streams.stream.0.sample_rate":
                        sampleRate = int.Parse(kv[1].Trim('"'), numberFormat);
                        break;

                    case "streams.stream.0.bits_per_sample":
                        bitsPerSample = int.Parse(kv[1].Trim('"'), numberFormat);
                        break;

                    case "streams.stream.0.duration":
                        durationInSeconds = double.Parse(kv[1].Trim('"'), numberFormat);
                        break;

                    case "streams.stream.0.channels":
                        channelCount = int.Parse(kv[1].Trim('"'), numberFormat);
                        break;
                    }
                }

                // This information is not available from ffprobe (and may or may not
                // be relevant for non-PCM formats anyway):
                //
                // * averageBytesPerSecond
                // * blockAlign

                this.duration = TimeSpan.FromSeconds(durationInSeconds);
                this.format   = new AudioFormat(
                    averageBytesPerSecond,
                    bitsPerSample,
                    blockAlign,
                    channelCount,
                    format,
                    sampleRate);
            }
            finally
            {
                File.Delete(temporarySource);
                File.Delete(temporaryOutput);
            }
        }
Ejemplo n.º 20
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="saveToFile">
        /// The name of the file that the converted audio should be saved into.  This is used for SongContent, where
        /// the audio is stored external to the XNB file.  If this is null, then the converted audio is stored in
        /// the Data property.
        /// </param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string saveToFile)
        {
            var temporarySource = Path.GetTempFileName();
            var temporaryOutput = Path.GetTempFileName();
            try
            {
                using (var fs = new FileStream(temporarySource, FileMode.Create, FileAccess.Write))
                {
                    var dataBytes = this.data.ToArray();
                    fs.Write(dataBytes, 0, dataBytes.Length);
                }

                string ffmpegCodecName, ffmpegMuxerName;
                int format;
                switch (formatType)
                {
                    case ConversionFormat.Adpcm:
                        // ADPCM Microsoft
                        ffmpegCodecName = "adpcm_ms";
                        ffmpegMuxerName = "wav";
                        format = 0x0002; /* WAVE_FORMAT_ADPCM */
                        break;
                    case ConversionFormat.Pcm:
                        // PCM signed 16-bit little-endian
                        ffmpegCodecName = "pcm_s16le";
                        ffmpegMuxerName = "wav";
                        format = 0x0001; /* WAVE_FORMAT_PCM */
                        break;
                    case ConversionFormat.WindowsMedia:
                        // Windows Media Audio 2
                        ffmpegCodecName = "wmav2";
                        ffmpegMuxerName = "asf";
                        format = 0x0161; /* WAVE_FORMAT_WMAUDIO2 */
                        break;
                    case ConversionFormat.Xma:
                        throw new NotSupportedException(
                            "XMA is not a supported encoding format. It is specific to the Xbox 360.");
                    case ConversionFormat.ImaAdpcm:
                        // ADPCM IMA WAV
                        ffmpegCodecName = "adpcm_ima_wav";
                        ffmpegMuxerName = "wav";
                        format = 0x0011; /* WAVE_FORMAT_IMA_ADPCM */
                        break;
                    case ConversionFormat.Aac:
                        // AAC (Advanced Audio Coding)
                        // Requires -strict experimental
                        ffmpegCodecName = "aac";
                        ffmpegMuxerName = "ipod";
                        format = 0x0000; /* WAVE_FORMAT_UNKNOWN */
                        break;
                    case ConversionFormat.Vorbis:
                        // Vorbis
                        ffmpegCodecName = "libvorbis";
                        ffmpegMuxerName = "ogg";
                        format = 0x0000; /* WAVE_FORMAT_UNKNOWN */
                        break;
                    default:
                        // Unknown format
                        throw new NotSupportedException();
                }

                string ffmpegStdout, ffmpegStderr;
                var ffmpegExitCode = ExternalTool.Run(
                    "ffmpeg",
                    string.Format(
                        "-y -i \"{0}\" -vn -c:a {1} -b:a {2} -f:a {3} -strict experimental \"{4}\"",
                        temporarySource,
                        ffmpegCodecName,
                        QualityToBitRate(quality),
                        ffmpegMuxerName,
                        temporaryOutput),
                    out ffmpegStdout,
                    out ffmpegStderr);
                if (ffmpegExitCode != 0)
                {
                    throw new InvalidOperationException("ffmpeg exited with non-zero exit code: \n" + ffmpegStdout + "\n" + ffmpegStderr);
                }

                byte[] rawData;
                using (var fs = new FileStream(temporaryOutput, FileMode.Open, FileAccess.Read))
                {
                    rawData = new byte[fs.Length];
                    fs.Read(rawData, 0, rawData.Length);
                }

                if (saveToFile != null)
                {
                    using (var fs = new FileStream(saveToFile, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(rawData, 0, rawData.Length);
                    }

                    this.data = null;
                }
                else
                {
                    this.data = rawData.ToList();
                }

                // Get the audio metadata from the output file
                string ffprobeStdout, ffprobeStderr;
                var ffprobeExitCode = ExternalTool.Run(
                    "ffprobe",
                    string.Format("-i \"{0}\" -show_entries streams -v quiet -of flat", temporaryOutput),
                    out ffprobeStdout,
                    out ffprobeStderr);
                if (ffprobeExitCode != 0)
                {
                    throw new InvalidOperationException("ffprobe exited with non-zero exit code.");
                }

                // Set default values if information is not available.
                int averageBytesPerSecond = 0;
                int bitsPerSample = 0;
                int blockAlign = 0;
                int channelCount = 0;
                int sampleRate = 0;
                double durationInSeconds = 0;

                var numberFormat = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
                foreach (var line in ffprobeStdout.Split(new[] { '\r', '\n', '\0' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var kv = line.Split(new[] { '=' }, 2);

                    switch (kv[0])
                    {
                        case "streams.stream.0.sample_rate":
                            sampleRate = int.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.bits_per_sample":
                            bitsPerSample = int.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.duration":
                            durationInSeconds = double.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.channels":
                            channelCount = int.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.bit_rate":
                            averageBytesPerSecond = (int.Parse(kv[1].Trim('"'), numberFormat) / 8);
                            break;
                    }
                }

                // Calculate blockAlign.
                switch (formatType)
                {
                    case ConversionFormat.Adpcm:
                    case ConversionFormat.ImaAdpcm:
                    case ConversionFormat.Pcm:
                        // Block alignment value is the number of bytes in an atomic unit (that is, a block) of audio for a particular format. For Pulse Code Modulation (PCM) formats, the formula for calculating block alignment is as follows:
                        //  •   Block Alignment = Bytes per Sample x Number of Channels
                        // For example, the block alignment value for 16-bit PCM format mono audio is 2 (2 bytes per sample x 1 channel). For 16-bit PCM format stereo audio, the block alignment value is 4.
                        // https://msdn.microsoft.com/en-us/library/system.speech.audioformat.speechaudioformatinfo.blockalign(v=vs.110).aspx
                        // Get the raw PCM from the output WAV file
                        using (var reader = new BinaryReader(new MemoryStream(rawData)))
                        {
                            data = GetRawWavData(reader, ref blockAlign).ToList();
                        }
                        break;
                    default:
                        // blockAlign is not available from ffprobe (and may or may not
                        // be relevant for non-PCM formats anyway)
                        break;
                }

                this.duration = TimeSpan.FromSeconds(durationInSeconds);
                this.format = new AudioFormat(
                    averageBytesPerSecond,
                    bitsPerSample,
                    blockAlign,
                    channelCount,
                    format,
                    sampleRate);

                // Loop start and length in number of samples. Defaults to entire sound
                loopStart = 0;
                if (data != null && bitsPerSample > 0 && channelCount > 0)
                    loopLength = data.Count / ((bitsPerSample / 8) * channelCount);
                else
                    loopLength = 0;
            }
            finally
            {
                File.Delete(temporarySource);
                File.Delete(temporaryOutput);
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Gets the file extension for an audio format.
 /// </summary>
 /// <param name="format">The conversion format</param>
 /// <returns>The file extension for the given conversion format.</returns>
 static public string GetExtension(ConversionFormat format)
 {
     return(conversionFormatExtensions[(int)format]);
 }
Ejemplo n.º 22
0
 public static extern IntPtr DdeClientTransaction(
     byte[] pData, int cbData, IntPtr hConv, IntPtr hszItem, ConversionFormat wFmt, int wType, int dwTimeout, ref int pdwResult);
Ejemplo n.º 23
0
 public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string saveToFile)
 {
     // Call the legacy conversion code.
     DefaultAudioProfile.ConvertToFormat(this, formatType, quality, saveToFile);
 }
Ejemplo n.º 24
0
		public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string targetFileName)
		{
			throw new NotImplementedException();
		}
Ejemplo n.º 25
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="saveToFile">
        /// The name of the file that the converted audio should be saved into.  This is used for SongContent, where
        /// the audio is stored external to the XNB file.  If this is null, then the converted audio is stored in
        /// the Data property.
        /// </param>
        public void ConvertFormat(ConversionFormat formatType, ConversionQuality quality, string saveToFile)
        {
            if (disposed)
                throw new ObjectDisposedException("AudioContent");

            var temporarySource = Path.GetTempFileName();
            var temporaryOutput = Path.GetTempFileName();
            try
            {
                using (var fs = new FileStream(temporarySource, FileMode.Create, FileAccess.Write))
                {
                    var dataBytes = this.data.ToArray();
                    fs.Write(dataBytes, 0, dataBytes.Length);
                }

                string ffmpegCodecName, ffmpegMuxerName;
                int format;
                switch (formatType)
                {
                    case ConversionFormat.Adpcm:
                        // ADPCM Microsoft 
                        ffmpegCodecName = "adpcm_ms";
                        ffmpegMuxerName = "wav";
                        format = 0x0002; /* WAVE_FORMAT_ADPCM */
                        break;
                    case ConversionFormat.Pcm:
                        // PCM signed 16-bit little-endian
                        ffmpegCodecName = "pcm_s16le";
                        ffmpegMuxerName = "s16le";
                        format = 0x0001; /* WAVE_FORMAT_PCM */
                        break;
                    case ConversionFormat.WindowsMedia:
                        // Windows Media Audio 2
                        ffmpegCodecName = "wmav2";
                        ffmpegMuxerName = "asf";
                        format = 0x0161; /* WAVE_FORMAT_WMAUDIO2 */
                        break;
                    case ConversionFormat.Xma:
                        throw new NotSupportedException(
                            "XMA is not a supported encoding format. It is specific to the Xbox 360.");
                    case ConversionFormat.ImaAdpcm:
                        // ADPCM IMA WAV
                        ffmpegCodecName = "adpcm_ima_wav";
                        ffmpegMuxerName = "wav";
                        format = 0x0011; /* WAVE_FORMAT_IMA_ADPCM */
                        break;
                    case ConversionFormat.Aac:
                        // AAC (Advanced Audio Coding)
                        // Requires -strict experimental
                        ffmpegCodecName = "aac";
                        ffmpegMuxerName = "ipod";
                        format = 0x0000; /* WAVE_FORMAT_UNKNOWN */
                        break;
                    case ConversionFormat.Vorbis:
                        // Vorbis
                        ffmpegCodecName = "libvorbis";
                        ffmpegMuxerName = "ogg";
                        format = 0x0000; /* WAVE_FORMAT_UNKNOWN */
                        break;
                    default:
                        // Unknown format
                        throw new NotSupportedException();
                }

                string ffmpegStdout, ffmpegStderr;
                var ffmpegExitCode = ExternalTool.Run(
                    "ffmpeg",
                    string.Format(
                        "-y -i \"{0}\" -vn -c:a {1} -b:a {2} -f:a {3} -strict experimental \"{4}\"",
                        temporarySource,
                        ffmpegCodecName,
                        QualityToBitRate(quality),
                        ffmpegMuxerName,
                        temporaryOutput),
                    out ffmpegStdout,
                    out ffmpegStderr);
                if (ffmpegExitCode != 0)
                {
                    throw new InvalidOperationException("ffmpeg exited with non-zero exit code: \n" + ffmpegStdout + "\n" + ffmpegStderr);
                }

                byte[] rawData;
                using (var fs = new FileStream(temporaryOutput, FileMode.Open, FileAccess.Read))
                {
                    rawData = new byte[fs.Length];
                    fs.Read(rawData, 0, rawData.Length);
                }

                if (saveToFile != null)
                {
                    using (var fs = new FileStream(saveToFile, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(rawData, 0, rawData.Length);
                    }

                    this.data = null;
                }
                else
                {
                    this.data = rawData.ToList();
                }

                string ffprobeStdout, ffprobeStderr;
                var ffprobeExitCode = ExternalTool.Run(
                    "ffprobe",
                    string.Format("-i \"{0}\" -show_entries streams -v quiet -of flat", temporarySource),
                    out ffprobeStdout,
                    out ffprobeStderr);
                if (ffprobeExitCode != 0)
                {
                    throw new InvalidOperationException("ffprobe exited with non-zero exit code.");
                }

                // Set default values if information is not available.
                int averageBytesPerSecond = 0;
                int bitsPerSample = 0;
                int blockAlign = 0;
                int channelCount = 0;
                int sampleRate = 0;
                double durationInSeconds = 0;

                var numberFormat = System.Globalization.CultureInfo.InvariantCulture.NumberFormat;
                foreach (var line in ffprobeStdout.Split(new[] { '\r', '\n', '\0' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    var kv = line.Split(new[] { '=' }, 2);

                    switch (kv[0])
                    {
                        case "streams.stream.0.sample_rate":
                            sampleRate = int.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.bits_per_sample":
                            bitsPerSample = int.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.duration":
                            durationInSeconds = double.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                        case "streams.stream.0.channels":
                            channelCount = int.Parse(kv[1].Trim('"'), numberFormat);
                            break;
                    }
                }

                // This information is not available from ffprobe (and may or may not
                // be relevant for non-PCM formats anyway):
                //
                // * averageBytesPerSecond
                // * blockAlign

                this.duration = TimeSpan.FromSeconds(durationInSeconds);
                this.format = new AudioFormat(
                    averageBytesPerSecond,
                    bitsPerSample,
                    blockAlign,
                    channelCount,
                    format,
                    sampleRate);
            }
            finally
            {
                File.Delete(temporarySource);
                File.Delete(temporaryOutput);
            }
        }
Ejemplo n.º 26
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.");
            }
        }