Beispiel #1
0
        /// <summary>
        ///     Plays a sound
        /// </summary>
        /// <param name="uid">Source of the sound</param>
        /// <param name="sound">The sound</param>
        /// <param name="excluded">Optional (server-side) argument used to prevent sending the audio to a specific
        /// user. When run client-side, exclusion does nothing.</param>
        private void PlaySound(EntityUid uid, SoundSpecifier?sound, AudioParams audioParams, EntityUid?excluded)
        {
            if (sound == null || !_gameTiming.IsFirstTimePredicted)
            {
                return;
            }

            var filter = Filter.Pvs(uid);

            if (excluded != null)
            {
                filter = filter.RemoveWhereAttachedEntity(entity => entity == excluded.Value);
            }

            SoundSystem.Play(filter, sound.GetSound(), uid, audioParams);
        }
    // TODO AUDIO PREDICT Figure out a better way to handle sound and prediction. For now, this works well enough?
    //
    // Currently a client will predict when a door is going to close automatically. So any client in PVS range can just
    // play their audio locally. Playing it server-side causes an odd delay, while in shared it causes double-audio.
    //
    // But if we just do that, then if a door is closed prematurely as the result of an interaction (i.e., using "E" on
    // an open door), then the audio would only be played for the client performing the interaction.
    //
    // So we do this:
    // - Play audio client-side IF the closing is being predicted (auto-close or predicted interaction)
    // - Server assumes automated closing is predicted by clients and does not play audio unless otherwise specified.
    // - Major exception is player interactions, which other players cannot predict
    // - In that case, send audio to all players, except possibly the interacting player if it was a predicted
    //   interaction.

    /// <summary>
    /// Selectively send sound to clients, taking care to not send the double-audio.
    /// </summary>
    /// <param name="uid">The audio source</param>
    /// <param name="sound">The sound</param>
    /// <param name="predictingPlayer">The user (if any) that instigated an interaction</param>
    /// <param name="predicted">Whether this interaction would have been predicted. If the predicting player is null,
    /// this assumes it would have been predicted by all players in PVS range.</param>
    protected override void PlaySound(EntityUid uid, string sound, AudioParams audioParams, EntityUid?predictingPlayer, bool predicted)
    {
        // If this sound would have been predicted by all clients, do not play any audio.
        if (predicted && predictingPlayer == null)
        {
            return;
        }

        var filter = Filter.Pvs(uid);

        if (predicted)
        {
            // This interaction is predicted, but only by the instigating user, who will have played their own sounds.
            filter.RemoveWhereAttachedEntity(e => e == predictingPlayer);
        }

        // send the sound to players.
        SoundSystem.Play(filter, sound, uid, audioParams);
    }
Beispiel #3
0
        public void CopyFrom(ItemSlot other)
        {
            // These fields are mutable reference types. But they generally don't get modified, so this should be fine.
            Whitelist   = other.Whitelist;
            InsertSound = other.InsertSound;
            EjectSound  = other.EjectSound;

            SoundOptions       = other.SoundOptions;
            Name               = other.Name;
            Locked             = other.Locked;
            InsertOnInteract   = other.InsertOnInteract;
            EjectOnInteract    = other.EjectOnInteract;
            EjectOnUse         = other.EjectOnUse;
            InsertVerbText     = other.InsertVerbText;
            EjectVerbText      = other.EjectVerbText;
            WhitelistFailPopup = other.WhitelistFailPopup;
            Swap               = other.Swap;
            Priority           = other.Priority;
        }
Beispiel #4
0
        /// <summary>
        /// Begins broadcast using the given VideoParams.
        /// </summary>
        /// <param name="videoParams">The video params</param>
        /// <returns>Whether or not successfully broadcasting</returns>
        public virtual bool StartBroadcasting(VideoParams videoParams)
        {
            if (videoParams == null || !this.IsReadyToBroadcast)
            {
                return(false);
            }

            m_VideoParams = videoParams.Clone() as VideoParams;

            // Setup the audio parameters
            m_AudioParams = new AudioParams();
            m_AudioParams.AudioEnabled = this.EnableAudio && this.IsAudioSupported; // only enable audio if possible

            if (!AllocateBuffers())
            {
                m_VideoParams = null;
                m_AudioParams = null;
                return(false);
            }

            ErrorCode ret = m_Stream.Start(videoParams, m_AudioParams, m_IngestServer, StartFlags.None, true);

            if (Error.Failed(ret))
            {
                CleanupBuffers();

                string err = Error.GetString(ret);
                ReportError(string.Format("Error while starting to broadcast: {0}", err));

                m_VideoParams = null;
                m_AudioParams = null;

                return(false);
            }

            SetBroadcastState(BroadcastState.Starting);

            return(true);
        }
Beispiel #5
0
        void IStreamCallbacks.StopCallback(ErrorCode ret)
        {
            if (Error.Succeeded(ret))
            {
                m_VideoParams = null;
                m_AudioParams = null;

                CleanupBuffers();

                try
                {
                    if (BroadcastStopped != null)
                    {
                        this.BroadcastStopped();
                    }
                }
                catch (Exception x)
                {
                    ReportError(x.ToString());
                }

                if (m_LoggedIn)
                {
                    SetBroadcastState(BroadcastState.ReadyToBroadcast);
                }
                else
                {
                    SetBroadcastState(BroadcastState.Initialized);
                }
            }
            else
            {
                // there's not really a good state to go into here
                SetBroadcastState(BroadcastState.ReadyToBroadcast);

                string err = Error.GetString(ret);
                ReportError(string.Format("StopCallback got failure: {0}", err));
            }
        }
Beispiel #6
0
    /// <summary>
    ///  Pick a sound from the pool and returns an Audio Source with the default values
    /// </summary>
    public AudioSource UpdateAudioSource(AudioSource audioSourceToUpdate)
    {
        int pickedNumber = 0;

        pickedNumber = UnityEngine.Random.Range(0, sounds.Count);
        AudioClip pickedSound = sounds[pickedNumber].clip;

        audioSourceToUpdate.clip         = pickedSound;
        audioSourceToUpdate.volume       = volume;
        audioSourceToUpdate.pitch        = pitch;
        audioSourceToUpdate.loop         = loop;
        audioSourceToUpdate.spatialBlend = spatialBlend;
        audioSourceToUpdate.rolloffMode  = AudioRolloffMode.Linear;
        audioSourceToUpdate.minDistance  = minDistance;
        audioSourceToUpdate.maxDistance  = maxDistance;
        audioSourceToUpdate.playOnAwake  = playOnAwake;
        if (audioMixerGroup != AudioParams.AudioMixerGroups.NONE)
        {
            audioSourceToUpdate.outputAudioMixerGroup = masterMixer.FindMatchingGroups(AudioParams.GetAudioMixerGroupName(audioMixerGroup))[0];
        }

        return(audioSourceToUpdate);
    }
Beispiel #7
0
        public void HandleTimerTrigger(EntityUid uid, EntityUid?user, float delay, float beepInterval, float?initialBeepDelay, SoundSpecifier?beepSound, AudioParams beepParams)
        {
            if (delay <= 0)
            {
                RemComp <ActiveTimerTriggerComponent>(uid);
                Trigger(uid, user);
                return;
            }

            if (HasComp <ActiveTimerTriggerComponent>(uid))
            {
                return;
            }

            if (user != null)
            {
                _logSystem.Add(LogType.Trigger,
                               $"{ToPrettyString(user.Value):user} started a {delay} second timer trigger on entity {ToPrettyString(uid):timer}");
            }
            else
            {
                _logSystem.Add(LogType.Trigger,
                               $"{delay} second timer trigger started on entity {ToPrettyString(uid):timer}");
            }

            var active = AddComp <ActiveTimerTriggerComponent>(uid);

            active.TimeRemaining = delay;
            active.User          = user;
            active.BeepParams    = beepParams;
            active.BeepSound     = beepSound;
            active.BeepInterval  = beepInterval;
            active.TimeUntilBeep = initialBeepDelay == null ? active.BeepInterval : initialBeepDelay.Value;

            if (TryComp <AppearanceComponent>(uid, out var appearance))
            {
                appearance.SetData(TriggerVisuals.VisualState, TriggerVisualState.Primed);
            }
        }
        public static void DecodeUsmFiles(FileInfo filename)
        {
            var  volume       = 1F;
            var  mode         = 16;
            var  loop         = 0;
            var  ciphKey1     = 0x92EBF464;
            uint ciphKey2     = 0x7E896318;
            var  path         = Directory.GetCurrentDirectory();
            var  cridCommands = " -a 92EBF464 -b 7E896318 -v -n \"" +
                                filename.FullName + "\"";

            Console.WriteLine(filename.Name + " - 解密m2v文件...");
            var process = new Process
            {
                StartInfo =
                {
                    FileName        = path + @"\crid.exe",
                    Arguments       = cridCommands,
                    UseShellExecute = true,
                    CreateNoWindow  = true
                }
            };

            process.Start();
            process.WaitForExit();
            var af     = new CriUsmStream(filename.FullName);
            var option = new MpegStream.DemuxOptionsStruct
            {
                ExtractAudio      = true,
                SplitAudioStreams = true
            };

            af.DemultiplexStreams(option);
            foreach (var hcafile in new DirectoryInfo(filename.DirectoryName).GetFiles("*.bin",
                                                                                       SearchOption.AllDirectories))
            {
                if (!hcafile.Name.Contains(filename.Name.Substring(0, filename.Name.Length - 4)))
                {
                    continue;
                }
                using (var inputFileStream = File.Open(hcafile.FullName, FileMode.Open, FileAccess.Read))
                {
                    Console.WriteLine(hcafile.Name + " - 解密hca...");
                    using (var outputFileStream =
                               File.Open(
                                   filename.DirectoryName + @"\" + filename.Name.Substring(0, filename.Name.Length - 4) +
                                   @".demux\" + hcafile.Name.Substring(0, hcafile.Name.Length - 4) + ".wav",
                                   FileMode.Create, FileAccess.Write))
                    {
                        var decodeParams = DecodeParams.CreateDefault();
                        decodeParams.Key1        = ciphKey1;
                        decodeParams.Key2        = ciphKey2;
                        decodeParams.KeyModifier = 0;

                        var audioParams = AudioParams.CreateDefault();

                        audioParams.InfiniteLoop       = AudioParams.Default.InfiniteLoop;
                        audioParams.SimulatedLoopCount = AudioParams.Default.SimulatedLoopCount;
                        audioParams.OutputWaveHeader   = true;

                        using (var hcaStream = new HcaAudioStream(inputFileStream, decodeParams, audioParams))
                        {
                            var read       = 1;
                            var dataBuffer = new byte[1024];

                            while (read > 0)
                            {
                                read = hcaStream.Read(dataBuffer, 0, dataBuffer.Length);

                                if (read > 0)
                                {
                                    outputFileStream.Write(dataBuffer, 0, read);
                                }
                            }
                        }
                    }
                }

                File.Delete(hcafile.FullName);
            }

            var m2vfiles = new DirectoryInfo(filename.DirectoryName + @"\" +
                                             filename.Name.Substring(0, filename.Name.Length - 4) + @".demux\")
                           .GetFiles("*.m2v", SearchOption.AllDirectories);
            var m2vfile  = m2vfiles[0];
            var wavfiles = new DirectoryInfo(filename.DirectoryName + @"\" +
                                             filename.Name.Substring(0, filename.Name.Length - 4) + @".demux\")
                           .GetFiles("*.wav", SearchOption.AllDirectories);
            var wavefile       = wavfiles[0];
            var ffmpegCommands = "-i " + "\"" + m2vfile.FullName + "\"" + " -i " + "\"" + wavefile.FullName + "\"" +
                                 " -c:v copy -c:a aac -strict experimental " + "\"" + filename.DirectoryName + @"\" +
                                 filename.Name.Substring(0, filename.Name.Length - 4) + @".demux\" +
                                 filename.Name.Substring(0, filename.Name.Length - 4) + "_final.mp4" + "\"";

            Console.WriteLine(filename.Name + " - 合并m2v、wav文件...");
            var process2 = new Process
            {
                StartInfo =
                {
                    FileName        = path + @"\ffmpeg.exe",
                    Arguments       = ffmpegCommands,
                    UseShellExecute = true,
                    CreateNoWindow  = true
                }
            };

            process2.Start();
            process2.WaitForExit();
        }
Beispiel #9
0
        public static void DecodeAcbFiles(FileInfo filename, DirectoryInfo AudioFolder)
        {
            var  volume   = 1F;
            var  mode     = 16;
            var  loop     = 0;
            var  ciphKey1 = 0x92EBF464;
            uint ciphKey2 = 0x7E896318;
            var  dir      = AudioFolder;
            var  dir2     = new DirectoryInfo(AudioFolder.FullName + @"\DecodedWavs\");
            var  acbfile  = filename;
            var  fs       = new FileStream(acbfile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var  af       = new CriAcbFile(fs, 0, false);

            af.ExtractAll();
            fs.Close();
            var destinationFolder = new DirectoryInfo(Path.Combine(acbfile.DirectoryName,
                                                                   "_vgmt_acb_ext_" + Path.GetFileNameWithoutExtension(acbfile.FullName)));
            var OutFolder =
                Path.Combine(Path.GetDirectoryName(acbfile.FullName.Replace(dir.FullName, dir2.FullName)),
                             Path.GetFileNameWithoutExtension(acbfile.FullName));

            Directory.CreateDirectory(OutFolder);

            Parallel.ForEach(destinationFolder.GetFiles("*.hca", SearchOption.AllDirectories), hcafile =>
            {
                using (var inputFileStream = File.Open(hcafile.FullName, FileMode.Open, FileAccess.Read))
                {
                    using (var outputFileStream =
                               File.Open(OutFolder + @"\" + hcafile.Name.Substring(0, hcafile.Name.Length - 4) + ".wav",
                                         FileMode.Create, FileAccess.Write))
                    {
                        var decodeParams         = DecodeParams.CreateDefault();
                        decodeParams.Key1        = ciphKey1;
                        decodeParams.Key2        = ciphKey2;
                        decodeParams.KeyModifier = 0;

                        var audioParams = AudioParams.CreateDefault();

                        audioParams.InfiniteLoop       = AudioParams.Default.InfiniteLoop;
                        audioParams.SimulatedLoopCount = AudioParams.Default.SimulatedLoopCount;
                        audioParams.OutputWaveHeader   = true;

                        using (var hcaStream = new HcaAudioStream(inputFileStream, decodeParams, audioParams))
                        {
                            var read       = 1;
                            var dataBuffer = new byte[1024];

                            while (read > 0)
                            {
                                read = hcaStream.Read(dataBuffer, 0, dataBuffer.Length);

                                if (read > 0)
                                {
                                    outputFileStream.Write(dataBuffer, 0, read);
                                }
                            }
                        }
                    }
                }

                File.Delete(hcafile.FullName);
            });
            var awbfilename = acbfile.FullName.Substring(0, acbfile.FullName.Length - 4) + ".awb";

            File.Delete(acbfile.FullName);
            File.Delete(awbfilename);
            Directory.Delete(destinationFolder.FullName, true);
        }
        /// <summary>
        /// Begins broadcast using the given VideoParams.
        /// </summary>
        /// <param name="videoParams">The video params</param>
        /// <returns>Whether or not successfully broadcasting</returns>
        public virtual bool StartBroadcasting(VideoParams videoParams)
        {
            if (videoParams == null || !this.IsReadyToBroadcast)
            {
                return false;
            }

            m_VideoParams = videoParams.Clone() as VideoParams;

            // Setup the audio parameters
            m_AudioParams = new AudioParams();
            m_AudioParams.AudioEnabled = this.EnableAudio && this.IsAudioSupported; // only enable audio if possible

            if (!AllocateBuffers())
            {
                m_VideoParams = null;
                m_AudioParams = null;
                return false;
            }

            ErrorCode ret = m_Stream.Start(videoParams, m_AudioParams, m_IngestServer, StartFlags.None, true);
            if (Error.Failed(ret))
            {
                CleanupBuffers();

                string err = Error.GetString(ret);
                ReportError(string.Format("Error while starting to broadcast: {0}", err));

                m_VideoParams = null;
                m_AudioParams = null;

                return false;
            }

            SetBroadcastState(BroadcastState.Starting);

            return true;
        }
Beispiel #11
0
        /// <summary>
        /// Begins the ingest testing.
        /// </summary>
        public void Start()
        {
            // can only run it once per instance
            if (m_TestState != TestState.Uninitalized)
            {
                return;
            }

            m_CurrentServerIndex = 0;
            m_CancelTest = false;
            m_SkipServer = false;

            m_PreviousStatCallbacks = m_Stream.StatCallbacks;
            m_Stream.StatCallbacks = this;

            m_PreviousStreamCallbacks = m_Stream.StreamCallbacks;
            m_Stream.StreamCallbacks = this;

            m_IngestTestVideoParams = new VideoParams();
            m_IngestTestVideoParams.TargetFps = Twitch.Broadcast.Constants.TTV_MAX_FPS;
            m_IngestTestVideoParams.MaxKbps = Twitch.Broadcast.Constants.TTV_MAX_BITRATE;
            m_IngestTestVideoParams.OutputWidth = 1280;
            m_IngestTestVideoParams.OutputHeight = 720;
            m_IngestTestVideoParams.PixelFormat = PixelFormat.TTV_PF_BGRA;
            m_IngestTestVideoParams.DisableAdaptiveBitrate = true;
            m_IngestTestVideoParams.VerticalFlip = false;

            m_Stream.GetDefaultParams(m_IngestTestVideoParams);

            m_IngestTestAudioParams = new AudioParams();
            m_IngestTestAudioParams.AudioEnabled = false;
            m_IngestTestAudioParams.EnableMicCapture = false;
            m_IngestTestAudioParams.EnablePlaybackCapture = false;
            m_IngestTestAudioParams.EnablePassthroughAudio = false;

            m_IngestBuffers = new List<UIntPtr>();

            // allocate some buffers
            int numFrames = 3;

            for (int i = 0; i < numFrames; ++i)
            {
                UIntPtr buffer = UIntPtr.Zero;
                uint size = m_IngestTestVideoParams.OutputWidth * m_IngestTestVideoParams.OutputHeight * 4;

                m_Stream.AllocateFrameBuffer(size, out buffer);

                if (buffer == UIntPtr.Zero)
                {
                    Cleanup();
                    SetTestState(TestState.Failed);
                    return;
                }

                m_Stream.RandomizeFrameBuffer(buffer, size);

                m_IngestBuffers.Add(buffer);
            }

            SetTestState(TestState.Starting);

            m_Timer.Reset();
            m_Timer.Start();
        }
Beispiel #12
0
        /// <summary>
        /// Begins the ingest testing.
        /// </summary>
        public void Start()
        {
            // can only run it once per instance
            if (m_TestState != TestState.Uninitalized)
            {
                return;
            }

            m_CurrentServerIndex = 0;
            m_CancelTest         = false;
            m_SkipServer         = false;

            m_PreviousStatCallbacks = m_Stream.StatCallbacks;
            m_Stream.StatCallbacks  = this;

            m_PreviousStreamCallbacks = m_Stream.StreamCallbacks;
            m_Stream.StreamCallbacks  = this;

            m_IngestTestVideoParams                        = new VideoParams();
            m_IngestTestVideoParams.TargetFps              = Twitch.Broadcast.Constants.TTV_MAX_FPS;
            m_IngestTestVideoParams.MaxKbps                = Twitch.Broadcast.Constants.TTV_MAX_BITRATE;
            m_IngestTestVideoParams.OutputWidth            = 1280;
            m_IngestTestVideoParams.OutputHeight           = 720;
            m_IngestTestVideoParams.PixelFormat            = PixelFormat.TTV_PF_BGRA;
            m_IngestTestVideoParams.DisableAdaptiveBitrate = true;
            m_IngestTestVideoParams.VerticalFlip           = false;

            m_Stream.GetDefaultParams(m_IngestTestVideoParams);

            m_IngestTestAudioParams = new AudioParams();
            m_IngestTestAudioParams.AudioEnabled = false;

            m_IngestBuffers = new List <UIntPtr>();

            // allocate some buffers
            int numFrames = 3;

            for (int i = 0; i < numFrames; ++i)
            {
                UIntPtr buffer = UIntPtr.Zero;
                uint    size   = m_IngestTestVideoParams.OutputWidth * m_IngestTestVideoParams.OutputHeight * 4;

                m_Stream.AllocateFrameBuffer(size, out buffer);

                if (buffer == UIntPtr.Zero)
                {
                    Cleanup();
                    SetTestState(TestState.Failed);
                    return;
                }

                m_Stream.RandomizeFrameBuffer(buffer, size);

                m_IngestBuffers.Add(buffer);
            }

            SetTestState(TestState.Starting);

            m_Timer.Reset();
            m_Timer.Start();
        }
        private void Start()
        {
            loginSuccess         = false;
            loginResultAvailable = false;
            loginReturn          = "";

            searchResultsAvailable = false;
            searchSuccess          = false;
            searchReturn           = "";

            lastSearch = DateTime.MinValue;
            _robotConnectionEstablished = false;

            Debug.Log(AnimusClient.AnimusClient.Version());

            _client = null;

            aparams            = new AudioParams();
            aparams.Channels   = 1;
            aparams.SampleRate = 16000;
            if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            {
                aparams.Backends.Clear();
                aparams.Backends.Add("winmm");
                aparams.TransmitRate = 10;
                aparams.SizeInFrames = false;
            }
            else if (Application.platform == RuntimePlatform.Android)
            {
                aparams.Backends.Clear();
                aparams.Backends.Add("opensl");
                aparams.TransmitRate = 10;
                aparams.SizeInFrames = false;
            }
            else if (Application.platform == RuntimePlatform.LinuxEditor || Application.platform == RuntimePlatform.LinuxPlayer)
            {
                aparams.Backends.Clear();
                aparams.Backends.Add("alsa");
                aparams.TransmitRate = 10;
                aparams.SizeInFrames = false;
            }

            var logdir = $"com.{Application.companyName}.{Application.productName}";

            var setupClient = new SetupClientProto();

            setupClient.AudioParams    = aparams;
            setupClient.LatencyLogging = true;
            setupClient.LogDir         = logdir;

            Debug.Log($"Logging to {logdir}");
            var setupReply = AnimusClient.AnimusClient.SetupClient(setupClient);

            if (!setupReply.Success)
            {
                Debug.Log(setupReply.Description);
            }
            else
            {
                Debug.Log("Client Setup completed successfully");
            }

#if PLATFORM_ANDROID
            if (!Permission.HasUserAuthorizedPermission(Permission.Microphone))
            {
                Permission.RequestUserPermission(Permission.Microphone);
            }
            if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageRead))
            {
                Permission.RequestUserPermission(Permission.ExternalStorageRead);
            }

            if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
            {
                Permission.RequestUserPermission(Permission.ExternalStorageWrite);
            }
#endif
        }
Beispiel #14
0
        private static int Main(string[] args)
        {
            const int defaultExitCodeFail = -1;

            var parser       = new Parser(settings => { settings.IgnoreUnknownArguments = true; });
            var parsedResult = parser.ParseArguments <Options>(args);

            var succeeded = parsedResult.Tag == ParserResultType.Parsed;

            Options options = null;

            if (succeeded)
            {
                options = ((Parsed <Options>)parsedResult).Value;
            }

            if (succeeded)
            {
                if (string.IsNullOrWhiteSpace(options.InputFileName))
                {
                    succeeded = false;
                }
            }

            if (!succeeded)
            {
                var helpText = CommandLine.Text.HelpText.AutoBuild(parsedResult, null, null);
                helpText.AddPreOptionsLine(" ");
                helpText.AddPreOptionsLine("Usage: hca2wav <input HCA> [options]");
                Console.Error.WriteLine(helpText);
                return(defaultExitCodeFail);
            }

            if (!File.Exists(options.InputFileName))
            {
                Console.Error.WriteLine("File not found: {0}", options.InputFileName);
                return(defaultExitCodeFail);
            }

            if (string.IsNullOrWhiteSpace(options.OutputFileName))
            {
                var fileInfo = new FileInfo(options.InputFileName);
                options.OutputFileName  = fileInfo.FullName.Substring(0, fileInfo.FullName.Length - fileInfo.Extension.Length);
                options.OutputFileName += ".wav";
            }

            uint   key1, key2;
            ushort keyModifier;
            var    formatProvider = new NumberFormatInfo();

            if (!string.IsNullOrWhiteSpace(options.Key1))
            {
                if (!uint.TryParse(options.Key1, NumberStyles.HexNumber, formatProvider, out key1))
                {
                    Console.WriteLine("ERROR: key 1 is in wrong format. It should look like \"a1b2c3d4\".");
                    return(defaultExitCodeFail);
                }
            }
            else
            {
                key1 = CgssCipher.Key1;
            }

            if (!string.IsNullOrWhiteSpace(options.Key2))
            {
                if (!uint.TryParse(options.Key2, NumberStyles.HexNumber, formatProvider, out key2))
                {
                    Console.WriteLine("ERROR: key 2 is in wrong format. It should look like \"a1b2c3d4\".");
                    return(defaultExitCodeFail);
                }
            }
            else
            {
                key2 = CgssCipher.Key2;
            }

            if (!string.IsNullOrWhiteSpace(options.KeyModifier))
            {
                if (!ushort.TryParse(options.KeyModifier, NumberStyles.HexNumber, formatProvider, out keyModifier))
                {
                    Console.WriteLine("ERROR: key modifier is in wrong format. It should look like \"abcd\".");
                    return(defaultExitCodeFail);
                }
            }
            else
            {
                keyModifier = 0;
            }

            using (var inputFileStream = File.Open(options.InputFileName, FileMode.Open, FileAccess.Read)) {
                using (var outputFileStream = File.Open(options.OutputFileName, FileMode.Create, FileAccess.Write)) {
                    var decodeParams = DecodeParams.CreateDefault();
                    decodeParams.Key1        = key1;
                    decodeParams.Key2        = key2;
                    decodeParams.KeyModifier = keyModifier;

                    if (options.OverridesCipherType)
                    {
                        decodeParams.CipherTypeOverrideEnabled = true;
                        decodeParams.OverriddenCipherType      = (CipherType)options.OverriddenCipherType;
                    }

                    var audioParams = AudioParams.CreateDefault();

                    audioParams.InfiniteLoop       = options.InfiniteLoop;
                    audioParams.SimulatedLoopCount = options.SimulatedLoopCount;
                    audioParams.OutputWaveHeader   = !options.NoWaveHeader;

                    using (var hcaStream = new HcaAudioStream(inputFileStream, decodeParams, audioParams)) {
                        var read       = 1;
                        var dataBuffer = new byte[1024];

                        while (read > 0)
                        {
                            read = hcaStream.Read(dataBuffer, 0, dataBuffer.Length);

                            if (read > 0)
                            {
                                outputFileStream.Write(dataBuffer, 0, read);
                            }
                        }
                    }
                }
            }

            return(0);
        }
Beispiel #15
0
        private static int Main(string[] args)
        {
            var options   = new Options();
            var succeeded = CommandLine.Parser.Default.ParseArguments(args, options);

            if (!succeeded)
            {
                Console.WriteLine(HelpMessage);
                return(CommandLine.Parser.DefaultExitCodeFail);
            }

            if (string.IsNullOrWhiteSpace(options.OutputFileName))
            {
                var fileInfo = new FileInfo(options.InputFileName);
                options.OutputFileName  = fileInfo.FullName.Substring(0, fileInfo.FullName.Length - fileInfo.Extension.Length);
                options.OutputFileName += ".wav";
            }

            uint key1, key2;
            var  formatProvider = new NumberFormatInfo();

            if (!string.IsNullOrWhiteSpace(options.Key1))
            {
                if (!uint.TryParse(options.Key1, NumberStyles.HexNumber, formatProvider, out key1))
                {
                    Console.WriteLine("ERROR: key 1 is of wrong format.");
                    return(CommandLine.Parser.DefaultExitCodeFail);
                }
            }
            else
            {
                key1 = CgssCipher.Key1;
            }
            if (!string.IsNullOrWhiteSpace(options.Key2))
            {
                if (!uint.TryParse(options.Key2, NumberStyles.HexNumber, formatProvider, out key2))
                {
                    Console.WriteLine("ERROR: key 2 is of wrong format.");
                    return(CommandLine.Parser.DefaultExitCodeFail);
                }
            }
            else
            {
                key2 = CgssCipher.Key2;
            }

            using (var inputFileStream = File.Open(options.InputFileName, FileMode.Open, FileAccess.Read)) {
                using (var outputFileStream = File.Open(options.OutputFileName, FileMode.Create, FileAccess.Write)) {
                    var decodeParams = DecodeParams.CreateDefault();
                    decodeParams.Key1 = key1;
                    decodeParams.Key2 = key2;
                    var audioParams = AudioParams.CreateDefault();
                    audioParams.InfiniteLoop       = options.InfiniteLoop;
                    audioParams.SimulatedLoopCount = options.SimulatedLoopCount;
                    audioParams.OutputWaveHeader   = options.OutputWaveHeader;
                    using (var hcaStream = new HcaAudioStream(inputFileStream, decodeParams, audioParams)) {
                        var read       = 1;
                        var dataBuffer = new byte[1024];
                        while (read > 0)
                        {
                            read = hcaStream.Read(dataBuffer, 0, dataBuffer.Length);
                            if (read > 0)
                            {
                                outputFileStream.Write(dataBuffer, 0, read);
                            }
                        }
                    }
                }
            }

            return(0);
        }
        /// <summary>
        /// Converts decoded, raw frame data in the frame source into a a usable frame. <br />
        /// The process includes performing picture, samples or text conversions
        /// so that the decoded source frame data is easily usable in multimedia applications
        /// </summary>
        /// <param name="input">The source frame to use as an input.</param>
        /// <param name="output">The target frame that will be updated with the source frame. If null is passed the frame will be instantiated.</param>
        /// <returns>
        /// Return the updated output frame
        /// </returns>
        /// <exception cref="System.ArgumentNullException">input</exception>
        internal override MediaBlock MaterializeFrame(MediaFrame input, ref MediaBlock output)
        {
            if (output == null)
            {
                output = new AudioBlock();
            }
            var source = input as AudioFrame;
            var target = output as AudioBlock;

            if (source == null || target == null)
            {
                throw new ArgumentNullException($"{nameof(input)} and {nameof(output)} are either null or not of a compatible media type '{MediaType}'");
            }

            // Create the source and target ausio specs. We might need to scale from
            // the source to the target
            var sourceSpec = AudioParams.CreateSource(source.Pointer);
            var targetSpec = AudioParams.CreateTarget(source.Pointer);

            // Initialize or update the audio scaler if required
            if (Scaler == null || LastSourceSpec == null || AudioParams.AreCompatible(LastSourceSpec, sourceSpec) == false)
            {
                Scaler = ffmpeg.swr_alloc_set_opts(Scaler, targetSpec.ChannelLayout, targetSpec.Format, targetSpec.SampleRate,
                                                   sourceSpec.ChannelLayout, sourceSpec.Format, sourceSpec.SampleRate, 0, null);

                ffmpeg.swr_init(Scaler);
                LastSourceSpec = sourceSpec;
            }

            // Allocate the unmanaged output buffer
            if (target.AudioBufferLength != targetSpec.BufferLength)
            {
                if (target.AudioBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(target.AudioBuffer);
                }

                target.AudioBufferLength = targetSpec.BufferLength;
                target.AudioBuffer       = Marshal.AllocHGlobal(targetSpec.BufferLength);
            }

            var outputBufferPtr = (byte *)target.AudioBuffer;

            // Execute the conversion (audio scaling). It will return the number of samples that were output
            var outputSamplesPerChannel =
                ffmpeg.swr_convert(Scaler, &outputBufferPtr, targetSpec.SamplesPerChannel,
                                   source.Pointer->extended_data, source.Pointer->nb_samples);

            // Compute the buffer length
            var outputBufferLength =
                ffmpeg.av_samples_get_buffer_size(null, targetSpec.ChannelCount, outputSamplesPerChannel, targetSpec.Format, 1);

            // set the target properties
            target.StartTime         = source.StartTime;
            target.EndTime           = source.EndTime;
            target.BufferLength      = outputBufferLength;
            target.ChannelCount      = targetSpec.ChannelCount;
            target.Duration          = source.Duration;
            target.SampleRate        = targetSpec.SampleRate;
            target.SamplesPerChannel = outputSamplesPerChannel;

            return(target);
        }
        void IStreamCallbacks.StartCallback(ErrorCode ret)
        {
            if (Error.Succeeded(ret))
            {
                try
                {
                    if (BroadcastStarted != null)
                    {
                        this.BroadcastStarted();
                    }
                }
                catch (Exception x)
                {
                    ReportError(x.ToString());
                }

                SetBroadcastState(BroadcastState.Broadcasting);
            }
            else
            {
                m_VideoParams = null;
                m_AudioParams = null;

                SetBroadcastState(BroadcastState.ReadyToBroadcast);

                string err = Error.GetString(ret);
                ReportError(string.Format("StartCallback got failure: {0}", err));
            }
        }
Beispiel #18
0
        /// <summary>
        /// Converts decoded, raw frame data in the frame source into a a usable frame. <br />
        /// The process includes performing picture, samples or text conversions
        /// so that the decoded source frame data is easily usable in multimedia applications
        /// </summary>
        /// <param name="input">The source frame to use as an input.</param>
        /// <param name="output">The target frame that will be updated with the source frame. If null is passed the frame will be instantiated.</param>
        /// <param name="siblings">The sibling blocks that may help guess some additional parameters for the input frame.</param>
        /// <returns>
        /// Return the updated output frame
        /// </returns>
        /// <exception cref="System.ArgumentNullException">input</exception>
        public override MediaBlock MaterializeFrame(MediaFrame input, ref MediaBlock output, List <MediaBlock> siblings)
        {
            if (output == null)
            {
                output = new AudioBlock();
            }
            var source = input as AudioFrame;
            var target = output as AudioBlock;

            if (source == null || target == null)
            {
                throw new ArgumentNullException($"{nameof(input)} and {nameof(output)} are either null or not of a compatible media type '{MediaType}'");
            }

            // Create the source and target ausio specs. We might need to scale from
            // the source to the target
            var sourceSpec = AudioParams.CreateSource(source.Pointer);
            var targetSpec = AudioParams.CreateTarget(source.Pointer);

            // Initialize or update the audio scaler if required
            if (Scaler == null || LastSourceSpec == null || AudioParams.AreCompatible(LastSourceSpec, sourceSpec) == false)
            {
                Scaler = ffmpeg.swr_alloc_set_opts(
                    Scaler,
                    targetSpec.ChannelLayout,
                    targetSpec.Format,
                    targetSpec.SampleRate,
                    sourceSpec.ChannelLayout,
                    sourceSpec.Format,
                    sourceSpec.SampleRate,
                    0,
                    null);

                RC.Current.Add(Scaler, $"109: {nameof(AudioComponent)}.{nameof(MaterializeFrame)}()");
                ffmpeg.swr_init(Scaler);
                LastSourceSpec = sourceSpec;
            }

            // Allocate the unmanaged output buffer
            if (target.AudioBufferLength != targetSpec.BufferLength)
            {
                if (target.AudioBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(target.AudioBuffer);
                }

                target.AudioBufferLength = targetSpec.BufferLength;
                target.AudioBuffer       = Marshal.AllocHGlobal(targetSpec.BufferLength);
            }

            var outputBufferPtr = (byte *)target.AudioBuffer;

            // Execute the conversion (audio scaling). It will return the number of samples that were output
            var outputSamplesPerChannel =
                ffmpeg.swr_convert(
                    Scaler,
                    &outputBufferPtr,
                    targetSpec.SamplesPerChannel,
                    source.Pointer->extended_data,
                    source.Pointer->nb_samples);

            // Compute the buffer length
            var outputBufferLength =
                ffmpeg.av_samples_get_buffer_size(null, targetSpec.ChannelCount, outputSamplesPerChannel, targetSpec.Format, 1);

            // Flag the block if we have to
            target.IsStartTimeGuessed = source.HasValidStartTime == false;

            // Try to fix the start time, duration and End time if we don't have valid data
            if (source.HasValidStartTime == false && siblings != null && siblings.Count > 0)
            {
                // Get timing information from the last sibling
                var lastSibling = siblings[siblings.Count - 1];

                // We set the target properties
                target.StartTime = lastSibling.EndTime;
                target.Duration  = source.Duration.Ticks > 0 ? source.Duration : lastSibling.Duration;
                target.EndTime   = TimeSpan.FromTicks(target.StartTime.Ticks + target.Duration.Ticks);
            }
            else
            {
                // We set the target properties directly from the source
                target.StartTime = source.StartTime;
                target.Duration  = source.Duration;
                target.EndTime   = source.EndTime;
            }

            target.BufferLength = outputBufferLength;
            target.ChannelCount = targetSpec.ChannelCount;

            target.SampleRate        = targetSpec.SampleRate;
            target.SamplesPerChannel = outputSamplesPerChannel;
            target.StreamIndex       = input.StreamIndex;

            return(target);
        }
        void IStreamCallbacks.StopCallback(ErrorCode ret)
        {
            if (Error.Succeeded(ret))
            {
                m_VideoParams = null;
                m_AudioParams = null;

                CleanupBuffers();

                try
                {
                    if (BroadcastStopped != null)
                    {
                        this.BroadcastStopped();
                    }
                }
                catch (Exception x)
                {
                    ReportError(x.ToString());
                }

                if (m_LoggedIn)
                {
                    SetBroadcastState(BroadcastState.ReadyToBroadcast);
                }
                else
                {
                    SetBroadcastState(BroadcastState.Initialized);
                }
            }
            else
            {
                // there's not really a good state to go into here
                SetBroadcastState(BroadcastState.ReadyToBroadcast);

                string err = Error.GetString(ret);
                ReportError(string.Format("StopCallback got failure: {0}", err));
            }
        }