Пример #1
0
        public int SDL_Init()
        {
            Callback = SDL_AudioCallback;
            #region SDL调用
            //// 初始化调用SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO | SDL.SDL_INIT_TIMER)
            //if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO | SDL.SDL_INIT_TIMER) < 0)
            //{
            //    Console.WriteLine("Could not initialize SDL - {0}\n", SDL.SDL_GetError());
            //    return -1;
            //}

            #endregion


            SDL.SDL_AudioSpec wanted_spec = new SDL.SDL_AudioSpec();
            wanted_spec.freq     = 8000;
            wanted_spec.format   = SDL.AUDIO_S16;
            wanted_spec.channels = 1;
            wanted_spec.silence  = 0;
            wanted_spec.samples  = 320;
            wanted_spec.callback = Callback;


            if (SDL.SDL_OpenAudio(ref wanted_spec, out SDL.SDL_AudioSpec obtained) < 0)
            {
                Console.WriteLine("can't open audio.");
                return(-1);
            }
            //Play
            SDL.SDL_PauseAudio(0);
            return(0);
        }
Пример #2
0
        public GusboyAudio(int sampleRate)
        {
            SDL.SDL_AudioSpec desiredSpec = new SDL.SDL_AudioSpec
            {
                freq     = sampleRate,
                format   = SDL.AUDIO_F32,
                channels = 2,
                samples  = 1024,
                userdata = IntPtr.Zero,
            };

            if ((this.device = SDL.SDL_OpenAudioDevice(null, 0, ref desiredSpec, out this.obtainedSpec, 0)) < 0)
            {
                Console.WriteLine($"ERROR: Couldn't open audio: {SDL.SDL_GetError()}");
                return;
            }

            // Console.WriteLine("Audio information:");
            // Console.WriteLine($"   Freq: {this.obtainedSpec.freq}");
            // Console.WriteLine($"   Channels: {this.obtainedSpec.channels}");
            // Console.WriteLine($"   Samples: {this.obtainedSpec.samples}");
            // Console.WriteLine($"   Size: {this.obtainedSpec.size}");
            // Console.WriteLine($"   Silence: {this.obtainedSpec.silence}");
            // Console.WriteLine($"   Format: {this.obtainedSpec.format}");
            this.obtainedSampleSize = (int)(this.obtainedSpec.size / this.obtainedSpec.samples / this.obtainedSpec.channels);

            SDL.SDL_PauseAudioDevice(this.device, 0);
        }
Пример #3
0
        public SDL.SDL_AudioSpec Inicializar(CPU cpu)
        {
            SDL.SDL_AudioSpec audioSpec = new SDL.SDL_AudioSpec();
            audioSpec.channels = 1;
            audioSpec.freq     = 44100;
            audioSpec.samples  = 256;
            audioSpec.format   = SDL.AUDIO_S8;
            audioSpec.callback = new SDL.SDL_AudioCallback((userdata, stream, length) =>
            {
                if (cpu == null)
                {
                    return;
                }

                sbyte[] waveData = new sbyte[length];

                for (int i = 0; i < waveData.Length && cpu.sound_timer > 0; i++, beepSamples++)
                {
                    if (beepSamples == 730)
                    {
                        beepSamples = 0;
                        cpu.sound_timer--;
                    }

                    waveData[i] = (sbyte)(127 * Math.Sin(sample * Math.PI * 2 * 604.1 / 44100));
                    sample++;
                }

                byte[] byteData = (byte[])(Array)waveData;

                Marshal.Copy(byteData, 0, stream, byteData.Length);
            });

            return(audioSpec);
        }
Пример #4
0
        public SDLAudioDevice(ref SDL.SDL_AudioSpec Desired, out SDL.SDL_AudioSpec Obtained)
        {
            myDeviceID = SDL.SDL_OpenAudioDevice(null, 0, ref Desired, out Obtained, (int)SDL.SDL_AUDIO_ALLOW_ANY_CHANGE);

            CheckDeviceID();

            myObtainedSpec = Obtained;
        }
Пример #5
0
        public SDLAudioDevice(ref SDL.SDL_AudioSpec Desired, out SDL.SDL_AudioSpec Obtained, int Allowed_Changes)
        {
            myDeviceID = SDL.SDL_OpenAudioDevice(null, 0, ref Desired, out Obtained, Allowed_Changes);

            CheckDeviceID();

            myObtainedSpec = Obtained;
        }
Пример #6
0
        public SDLAudioDevice(string Device, bool Iscapture, ref SDL.SDL_AudioSpec Desired, out SDL.SDL_AudioSpec Obtained, int Allowed_Changes)
        {
            myDeviceID = SDL.SDL_OpenAudioDevice(Device, Convert.ToInt32(Iscapture), ref Desired, out Obtained, Allowed_Changes);

            CheckDeviceID();

            myObtainedSpec = Obtained;
        }
Пример #7
0
        public static void Init()
        {
            var spec = new SDL.SDL_AudioSpec();

            spec.freq     = SampleRate;
            spec.format   = SDL.AUDIO_F32;
            spec.channels = 2;
            spec.samples  = 4096;
            spec.callback = MixAudio;
            _audioDevice  = SDL.SDL_OpenAudioDevice(null, 0, ref spec, out _audioSpec, 0);
            int len = _audioSpec.samples * 2;

            _buffer     = new float[len];
            _tempBuffer = new float[len];
            SDL.SDL_PauseAudioDevice(_audioDevice, 0); // Start playing
            _lastRenderTime = DateTime.Now;
        }
Пример #8
0
        public bool SetDevice(ushort sampleRate, ushort bufferSize, Func <byte> getSample)
        {
            GetSample = getSample;
            SDL.SDL_AudioSpec wanted = new SDL.SDL_AudioSpec();

            sudata sud    = new sudata();
            bool   result = false;

            wanted.freq     = sampleRate;
            wanted.samples  = bufferSize;
            wanted.channels = 1;
            wanted.format   = SDL.AUDIO_S16;
            wanted.userdata = Marshal.AllocHGlobal(Marshal.SizeOf(sud));
            wanted.callback = pFillAudio;

            if ((SDL.SDL_InitSubSystem(SDL.SDL_INIT_AUDIO)) == 0)
            {
                if ((SDL.SDL_OpenAudio(ref wanted, out sud.obtained)) == 0)
                {
                    result = true;
                }
            }

            if (result == false)
            {
                Log.Write($"Couldn't open audio: {SDL.SDL_GetError()}");
                Marshal.FreeHGlobal(wanted.userdata);
                return(false);
            }

            sud.bsize = sud.obtained.size;
            sud.buf   = Marshal.AllocHGlobal((int)sud.bsize);

            sud.lp_fltr = Calc.bqd_lp_init(sud.obtained.freq, 4000).ToPointer();
            sud.hp_fltr = Calc.bqd_hp_init(sud.obtained.freq, 1000).ToPointer();

            Marshal.StructureToPtr(sud, wanted.userdata, false);
            IsWaveDeviceAvailable = true;

            return(result);
        }
Пример #9
0
        public int SDL_Init(AVCodecContext *audioCtx)
        {
            Callback = SDL_AudioCallback;

            SDL.SDL_AudioSpec wanted_spec = new SDL.SDL_AudioSpec();
            wanted_spec.freq     = audioCtx->sample_rate;
            wanted_spec.format   = SDL.AUDIO_F32;
            wanted_spec.channels = (byte)audioCtx->channels;
            wanted_spec.silence  = 0;
            wanted_spec.samples  = 1024;
            wanted_spec.callback = Callback;

            if (SDL.SDL_OpenAudio(ref wanted_spec, IntPtr.Zero) < 0)
            {
                Console.WriteLine("can't open audio.");
                return(-1);
            }
            //Play
            SDL.SDL_PauseAudio(0);
            return(0);
        }
Пример #10
0
        public int Initialize(int samples)
        {
            var desired  = new SDL.SDL_AudioSpec();
            var obtained = new SDL.SDL_AudioSpec();

            int ret = SDL.SDL_Init(SDL.SDL_INIT_AUDIO);

            if (ret < 0)
            {
                Debug.WriteLine($"SDL_Init AUDIO failed: {SDL.SDL_GetError()}");
                return(1);
            }

            desired.freq     = _sampleRate;
            desired.format   = SDL.AUDIO_F32;
            desired.channels = (byte)_channels;
            desired.samples  = (ushort)samples;

            _dev = SDL.SDL_OpenAudioDevice(
                device: null,
                iscapture: 0,
                desired: ref desired,
                obtained: out obtained,
                allowed_changes: (int)SDL.SDL_AUDIO_ALLOW_FORMAT_CHANGE);

            if (_dev == 0)
            {
                Debug.WriteLine($"Failed to open audio: {SDL.SDL_GetError()}");
                return(1);
            }

            if (obtained.format != desired.format)
            { /* we let this one thing change. */
                Debug.WriteLine($"We didn't get Float32 audio format.");
            }
            SDL.SDL_PauseAudioDevice(_dev, 0); /* start audio playing. */

            return(0);
        }
Пример #11
0
        static void Loop()
        {
            while (SDL.SDL_PollEvent(out ev) > 0)
            {
                switch (ev.type)
                {
                case SDL.SDL_EventType.SDL_QUIT:
                    break;

                default:
                    break;
                }
            }

            if (w > 0 && IntPtr.Zero == mtex)
            {
                mtex    = SDL.SDL_CreateTexture(mrender, SDL.SDL_PIXELFORMAT_IYUV, (int)SDL.SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING, w, h);
                mrect.h = h;
                mrect.w = w;
                mrect.x = mrect.y = 0;
                int ysize = w * h;
                ydata = new byte[(int)(ysize)];
                udata = new byte[ysize / 4];
                vdata = new byte[ysize / 4];
                wanted_spec.channels = 2;
                wanted_spec.format   = SDL.AUDIO_F32;
                wanted_spec.freq     = 44100;
                wanted_spec.silence  = 0;
                wanted_spec.samples  = 1500;
                wanted_spec.callback = SDLCALL;
                SDL.SDL_AudioSpec out_spec = new SDL.SDL_AudioSpec();
                SDL.SDL_OpenAudio(ref wanted_spec, out out_spec);
                SDL.SDL_PauseAudio(0);
            }

            BSPDMS.GetRawData(ydata, udata, vdata);

            Update();
        }
Пример #12
0
 public static extern void SMPEG_actualSpec(SMPEGPtr mpeg, ref SDL.SDL_AudioSpec spec);
Пример #13
0
 public SDLAudioDevice GetAudioDevice(out SDL.SDL_AudioSpec Obtained)
 {
     return(new SDLAudioDevice(ref myAudioSpec, out Obtained));
 }
Пример #14
0
        static void Main(string[] args)
        {
            if (SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING) < 0)
            {
                Console.WriteLine("SDL failed to init.");
                return;
            }

            IntPtr window = SDL.SDL_CreateWindow("Chip-8 Interpreter", 128, 128, 64 * 8, 32 * 8, 0);

            if (window == IntPtr.Zero)
            {
                Console.WriteLine("SDL could not create a window.");
                return;
            }

            IntPtr renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED);

            if (renderer == IntPtr.Zero)
            {
                Console.WriteLine("SDL could not create a valid renderer.");
                return;
            }

            CPU cpu = new CPU();

            using (BinaryReader reader = new BinaryReader(new FileStream("../../sample.ch8", FileMode.Open)))
            {
                List <byte> program = new List <byte>();

                while (reader.BaseStream.Position < reader.BaseStream.Length)
                {
                    program.Add(reader.ReadByte());
                }

                cpu.LoadProgram(program.ToArray());
            }

            SDL.SDL_Event sdlEvent;
            bool          running = true;

            int sample      = 0;
            int beepSamples = 0;

            SDL.SDL_AudioSpec audioSpec = new SDL.SDL_AudioSpec();
            audioSpec.channels = 1;
            audioSpec.freq     = 44100;
            audioSpec.samples  = 256;
            audioSpec.format   = SDL.AUDIO_S8;
            audioSpec.callback = new SDL.SDL_AudioCallback((userdata, stream, length) =>
            {
                if (cpu == null)
                {
                    return;
                }

                sbyte[] waveData = new sbyte[length];

                for (int i = 0; i < waveData.Length && cpu.SoundTimer > 0; i++, beepSamples++)
                {
                    if (beepSamples == 730)
                    {
                        beepSamples = 0;
                        cpu.SoundTimer--;
                    }

                    waveData[i] = (sbyte)(127 * Math.Sin(sample * Math.PI * 2 * 604.1 / 44100));
                    sample++;
                }

                byte[] byteData = (byte[])(Array)waveData;

                Marshal.Copy(byteData, 0, stream, byteData.Length);
            });

            SDL.SDL_OpenAudio(ref audioSpec, IntPtr.Zero);
            SDL.SDL_PauseAudio(0);

            IntPtr    sdlSurface, sdlTexture = IntPtr.Zero;
            Stopwatch frameTimer   = Stopwatch.StartNew();
            int       ticksPer60hz = (int)(Stopwatch.Frequency * 0.016);

            while (running)
            {
                try
                {
                    if (!cpu.WaitingForKeyPress)
                    {
                        cpu.Step();
                    }

                    if (frameTimer.ElapsedTicks > ticksPer60hz)
                    {
                        while (SDL.SDL_PollEvent(out sdlEvent) != 0)
                        {
                            if (sdlEvent.type == SDL.SDL_EventType.SDL_QUIT)
                            {
                                running = false;
                            }
                            else if (sdlEvent.type == SDL.SDL_EventType.SDL_KEYDOWN)
                            {
                                var key = KeyCodeToKey((int)sdlEvent.key.keysym.sym);
                                cpu.Keyboard |= (ushort)(1 << key);

                                if (cpu.WaitingForKeyPress)
                                {
                                    cpu.KeyPressed((byte)key);
                                }
                            }
                            else if (sdlEvent.type == SDL.SDL_EventType.SDL_KEYUP)
                            {
                                var key = KeyCodeToKey((int)sdlEvent.key.keysym.sym);
                                cpu.Keyboard &= (ushort)~(1 << key);
                            }
                        }

                        var displayHandle = GCHandle.Alloc(cpu.Display, GCHandleType.Pinned);

                        if (sdlTexture != IntPtr.Zero)
                        {
                            SDL.SDL_DestroyTexture(sdlTexture);
                        }

                        sdlSurface = SDL.SDL_CreateRGBSurfaceFrom(displayHandle.AddrOfPinnedObject(), 64, 32, 32, 64 * 4, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
                        sdlTexture = SDL.SDL_CreateTextureFromSurface(renderer, sdlSurface);

                        displayHandle.Free();

                        SDL.SDL_RenderClear(renderer);
                        SDL.SDL_RenderCopy(renderer, sdlTexture, IntPtr.Zero, IntPtr.Zero);
                        SDL.SDL_RenderPresent(renderer);

                        frameTimer.Restart();
                    }

                    Thread.Sleep(1);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }

            SDL.SDL_DestroyRenderer(renderer);
            SDL.SDL_DestroyWindow(window);
        }
Пример #15
0
 public SDLAudioDevice GetAudioDevice(out SDL.SDL_AudioSpec Obtained, int Allowed_Changes)
 {
     return(new SDLAudioDevice(ref myAudioSpec, out Obtained, Allowed_Changes));
 }
Пример #16
0
 public SDLAudioDevice GetAudioDevice(string Device, bool Iscapture, out SDL.SDL_AudioSpec Obtained, int Allowed_Changes)
 {
     return(new SDLAudioDevice(Device, Iscapture, ref myAudioSpec, out Obtained, Allowed_Changes));
 }
Пример #17
0
        public AudioEngine(string audioDevice = null, AudioDriver driver = AudioDriver.Default, int sampleRate = 44100, int bufferLength = 1024, ResampleQuality resampleQuality = ResampleQuality.High)
        {
            this.resampleQuality = resampleQuality;

            SDL.SDL_InitSubSystem(SDL.SDL_INIT_AUDIO);

            audioCallback = AudioCallback;
            SDL.SDL_AudioSpec desired = new SDL.SDL_AudioSpec()
            {
                freq     = sampleRate,
                format   = SDL.AUDIO_S16,
                channels = 2,
                samples  = (ushort)bufferLength,
                callback = audioCallback,
            };

            if (driver == AudioDriver.File)
            {
                audioSpec   = desired;
                audioDriver = driver;
            }
            else
            {
                string[] audioDrivers = new string[SDL.SDL_GetNumAudioDrivers()];
                for (int i = 0; i < audioDrivers.Length; i++)
                {
                    audioDrivers[i] = SDL.SDL_GetAudioDriver(i);
                }

                string driverName         = audioDrivers[0];
                string driverFallbackName = audioDrivers.Length > 1 ? audioDrivers[1] : null;

                if (driver != AudioDriver.Default)
                {
                    driverName = driver.ToString();
                }

                int init = SDL.SDL_AudioInit(driverName.ToLower());
                if (init != 0 && driverName == AudioDriver.XAudio2.ToString().ToLower() && driverFallbackName != null)
                {
                    // supplied SDL.dll does not support XAudio2, fallback to next driver
                    driverName = driverFallbackName;
                    init       = SDL.SDL_AudioInit(driverName.ToLower());
                }
                if (init != 0)
                {
                    throw new ApplicationException("Failed to initialize audio driver " + driverName + ": " + SDL.SDL_GetError());
                }

                Enum.TryParse(driverName, true, out audioDriver);

                if (audioDevice == null)
                {
                    string[] audioDevices = new string[SDL.SDL_GetNumAudioDevices(0)];
                    for (int i = 0; i < audioDevices.Length; i++)
                    {
                        audioDevices[i] = SDL.SDL_GetAudioDeviceName(i, 0);
                    }

                    audioDevice = audioDevices.Length > 0 ? audioDevices[0] : null;
                }

                outputDevice = SDL.SDL_OpenAudioDevice(audioDevice, 0, ref desired, out audioSpec, 0);
                if (outputDevice == 0)
                {
                    throw new ApplicationException("Failed to open audio device " + audioDevice + ": " + SDL.SDL_GetError());
                }
            }

            if (audioSpec.format == SDL.AUDIO_S32)
            {
                bytesPerSample = (uint)audioSpec.channels * 4;
            }
            else if (audioSpec.format == SDL.AUDIO_S16 || audioSpec.format == SDL.AUDIO_F32)
            {
                bytesPerSample = (uint)audioSpec.channels * 2;
            }
            else if (audioSpec.format == SDL.AUDIO_S8 || audioSpec.format == SDL.AUDIO_U8)
            {
                bytesPerSample = (uint)audioSpec.channels * 1;
            }

            if (audioSpec.size == 0)
            {
                audioSpec.size = audioSpec.samples * bytesPerSample;
            }

            emptyBuffer = new byte[audioSpec.size];
            audioBuffer = new byte[audioSpec.size];

            lastCallback = 0.0;
            bufferTimer  = Stopwatch.StartNew();

            if (outputDevice != 0)
            {
                SDL.SDL_PauseAudioDevice(outputDevice, 0);
            }
        }
Пример #18
0
        /**
         * Used to initialize the GUI by creating a window using SDL. This window is where the framebuffer
         * will be rendered. This method must be called before any other methods.
         */
        public void Initialize(string title, int width = 640, int height = 480, float scaleX = 1, float scaleY = 1, int targetTicskHz = 60)
        {
            var initResult = SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO | SDL.SDL_INIT_GAMECONTROLLER);

            if (initResult != 0)
            {
                throw new Exception(String.Format("Failure while initializing SDL. SDL Error: {0}", SDL.SDL_GetError()));
            }

            _isWinRT = SDL.SDL_GetPlatform() == "WinRT";

            _gameWindow = SDL.SDL_CreateWindow(title,
                                               SDL.SDL_WINDOWPOS_CENTERED,
                                               SDL.SDL_WINDOWPOS_CENTERED,
                                               (int)(width * scaleX),
                                               (int)(height * scaleY),
                                               SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE
                                               );

            if (_gameWindow == IntPtr.Zero)
            {
                throw new Exception(String.Format("Unable to create a window. SDL Error: {0}", SDL.SDL_GetError()));
            }

            _gameRendererSurface = SDL.SDL_CreateRenderer(_gameWindow, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED /*| SDL.SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC*/);

            if (_gameRendererSurface == IntPtr.Zero)
            {
                throw new Exception(String.Format("Unable to create a renderer. SDL Error: {0}", SDL.SDL_GetError()));
            }

            // We can scale the image up or down based on the scaling factor.
            SDL.SDL_RenderSetScale(_gameRendererSurface, scaleX, scaleY);

            // By setting the logical size we ensure that the image will scale to fit the window while
            // still maintaining the original aspect ratio.
            SDL.SDL_RenderSetLogicalSize(_gameRendererSurface, width, height);

            _targetTicksHz = targetTicskHz;

            // Setup our audio format.
            SDL.SDL_AudioSpec audioSpec = new SDL.SDL_AudioSpec();
            audioSpec.freq = 96000; // sampling rate
            // audioSpec.freq = 44100; // sampling rate
            // audioSpec.freq = 22050; // sampling rate
            // audioSpec.freq = 11025; // sampling rate
            audioSpec.format   = SDL.AUDIO_S8; // sample format: 8-bit, signed
            audioSpec.channels = 1;            // number of channels
            audioSpec.samples  = 4096;         // buffer size

            SDL.SDL_AudioSpec audioSpecObtained;

            // Open the default audio device.
            _audioDevice = SDL.SDL_OpenAudioDevice(null, 0, ref audioSpec, out audioSpecObtained, 0);

            if (_audioDevice == 0)
            {
                throw new Exception(String.Format("Unable to open the audio device. SDL Error: {0}", SDL.SDL_GetError()));
            }

            // Unpause the audio device and so that it will play once samples are queued up.
            SDL.SDL_PauseAudioDevice(_audioDevice, 0);

            // Attempt to open controllers.

            var numJoysticks = SDL.SDL_NumJoysticks();

            for (var i = 0; i < numJoysticks; i++)
            {
                if (SDL.SDL_IsGameController(i) == SDL.SDL_bool.SDL_FALSE)
                {
                    continue;
                }

                var controller = SDL.SDL_GameControllerOpen(i);

                if (controller != IntPtr.Zero)
                {
                    _controllers.Add(controller);
                }
            }
        }
Пример #19
0
        public SDLWAV(string File, ref SDL.SDL_AudioSpec Spec)
        {
            myAudioSpec = SDL.SDL_LoadWAV(File, ref Spec, out myAudio_Buf, out myAudio_Len);

            myFile = File;
        }
Пример #20
0
 public static extern int SMPEG_wantedSpec(SMPEGPtr mpeg, ref SDL.SDL_AudioSpec wanted);
Пример #21
0
        /// <summary>
        /// mpegファイルを読み込む
        /// </summary>
        /// <param name="filename">ファイル名</param>
        public YanesdkResult Load(string filename)
        {
            lock (lockObject)
            {
                Release();
                tmpFile = FileSys.GetTmpFile(filename);
                if (tmpFile == null || tmpFile.FileName == null)
                {
                    return(YanesdkResult.FileNotFound);
                }
                // 読み込み。
                //mpeg = SMPEG.SMPEG_new(tmpFile.FileName, ref info, SDL.SDL_WasInit(SDL.SDL_INIT_AUDIO) == 0 ? 1 : 0);
                mpeg = SMPEG.SMPEG_new(tmpFile.FileName, ref info, 0);
                if (SMPEG.SMPEG_error(mpeg) != null)
                {
                    Debug.Fail(SMPEG.SMPEG_error(mpeg));
                    return(YanesdkResult.SdlError);                    // …SDL?
                }

                // 初期設定
                //	loop = false;
                // ループ設定はここでは変更しないほうが良い。

                paused = false;

                SMPEG.SMPEG_enablevideo(mpeg, 1);
                SMPEG.SMPEG_enableaudio(mpeg, 0);
                if (info.has_audio != 0)
                {
                    SDL.SDL_AudioSpec audiofmt = new SDL.SDL_AudioSpec();
                    audiofmt.format   = (ushort)Sound.Sound.SoundConfig.AudioFormat;
                    audiofmt.freq     = (ushort)Sound.Sound.SoundConfig.AudioRate;
                    audiofmt.channels = (byte)Sound.Sound.SoundConfig.AudioChannels;
                    audiofmt.samples  = (ushort)Sound.Sound.SoundConfig.AudioBuffers;
                    SMPEG.SMPEG_actualSpec(mpeg, ref audiofmt);
                    SDL.Mix_HookMusic(mix_hook, mpeg);
                    SMPEG.SMPEG_enableaudio(mpeg, 1);
                }
                SMPEG.SMPEG_enableaudio(mpeg, 1);
                Volume = volume;

                // 描画先サーフェスのsmpegへの登録など。
                if (window != null)
                {
                    // SDLWindowに直に描画する

                    if (surface != null)
                    {
                        surface.Dispose();
                        surface = null;
                    }

                    uint flags = (uint)window.Option;
                    flags &= ~SDL.SDL_OPENGL;                     // OPENGLはダメ。
                    IntPtr s = SDL.SDL_SetVideoMode(window.Width, window.Height, window.Bpp, flags);
                    if (s == IntPtr.Zero)
                    {
                        return(YanesdkResult.SdlError);
                    }

                    SMPEG.SMPEG_setdisplay(mpeg, s, IntPtr.Zero, null);
                    SMPEG.SMPEG_move(mpeg, (int)windowRect.Left, (int)windowRect.Top);
                    SMPEG.SMPEG_scaleXY(mpeg, (int)windowRect.Width, (int)windowRect.Height);
                }
                else if (
                    Yanesdk.System.Platform.PlatformID == Yanesdk.System.PlatformID.Windows &&
                    hwnd != IntPtr.Zero)
                {
                    // SDLWindowを貼り付けてそれに描画する

                    if (surface != null)
                    {
                        surface.Dispose();
                        surface = null;
                    }

                    // 親ウィンドウの位置・サイズを取得
                    POINT parentPos = new POINT();
                    ClientToScreen(hwnd, ref parentPos);
                    RECT parentRect = new RECT();
                    GetClientRect(hwnd, out parentRect);
                    int w = parentRect.right - parentRect.left, h = parentRect.bottom - parentRect.top;

                    // SDLウィンドウの位置を合わせる
                    IntPtr sdlHwnd = GetSDLWindowHandle();
                    //SetParent(sdlHwnd, hwnd); // これするとどうもバグる…
                    SetWindowPos(sdlHwnd, IntPtr.Zero, parentPos.x, parentPos.y, w, h, SWP_NOZORDER);

                    // SDLウィンドウの作成
                    uint   flags = SDL.SDL_HWSURFACE | SDL.SDL_NOFRAME;
                    IntPtr s     = SDL.SDL_SetVideoMode(w, h, 0, flags);
                    if (s == IntPtr.Zero)
                    {
                        return(YanesdkResult.SdlError);
                    }

                    sdlWindowCreated = true;

                    sdlHwnd = GetSDLWindowHandle();                     // 変わらないと思うが、一応再取得
                    if (sdlHwnd == IntPtr.Zero)
                    {
                        return(YanesdkResult.SdlError);
                    }
                    SetParent(sdlHwnd, hwnd);
                    SetWindowPos(sdlHwnd, IntPtr.Zero, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOSIZE);

                    SMPEG.SMPEG_setdisplay(mpeg, s, IntPtr.Zero, null);
                    SMPEG.SMPEG_move(mpeg, 0, 0);
                    SMPEG.SMPEG_scaleXY(mpeg, w, h);
                }
                else
                {
                    // surfaceに描画する

                    if (surface != null && (!surface.CheckRGB888() ||
                                            surface.Width != Width || surface.Height != Height))
                    {
                        surface.Dispose();
                        surface = null;
                    }
                    if (surface == null)
                    {
                        surface = new Surface();
                        // 拡大・縮小はSMPEG側にやらせると重いので、原寸大で。
                        YanesdkResult result = surface.CreateDIB(Width, Height, false);
                        if (result != YanesdkResult.NoError)
                        {
                            return(result);
                        }
                    }

                    SMPEG.SMPEG_setdisplay(mpeg, surface.SDL_Surface, mutex, callback);
                    SMPEG.SMPEG_move(mpeg, 0, 0);
                    SMPEG.SMPEG_scaleXY(mpeg, surface.Width, surface.Height);
                    //SetFilter(SMPEG.SMPEGfilter_null());
                }

                this.fileName = filename;

                // おしまい。
                return(YanesdkResult.NoError);
            }
        }
Пример #22
0
        private void InitializeSDL()
        {
            int retVal;

            SDL.SDL_SetHint("SDL_WINDOWS_DISABLE_THREAD_NAMING", "1");

            // Get SDL humming
            if ((retVal = SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING)) < 0)
            {
                throw new InvalidOperationException(String.Format("SDL_Init failed.  Error {0:x}", retVal));
            }

            //
            if (SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_SCALE_QUALITY, "0") == SDL.SDL_bool.SDL_FALSE)
            {
                throw new InvalidOperationException("SDL_SetHint failed to set scale quality.");
            }

            _sdlWindow = SDL.SDL_CreateWindowFrom(DisplayBox.Handle);

            if (_sdlWindow == IntPtr.Zero)
            {
                throw new InvalidOperationException("SDL_CreateWindow failed.");
            }

            if (Configuration.Platform == PlatformType.Unix)
            {
                // On UNIX platforms it appears that asking for hardware acceleration causes SDL_CreateRenderer
                // to hang indefinitely.  For the time being, we'll default to software rendering.
                _sdlRenderer = SDL.SDL_CreateRenderer(_sdlWindow, -1, SDL.SDL_RendererFlags.SDL_RENDERER_SOFTWARE);

                if (_sdlRenderer == IntPtr.Zero)
                {
                    // No luck.
                    throw new InvalidOperationException("SDL_CreateRenderer failed.");
                }
            }
            else
            {
                _sdlRenderer = SDL.SDL_CreateRenderer(_sdlWindow, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED);
                if (_sdlRenderer == IntPtr.Zero)
                {
                    // Fall back to software
                    _sdlRenderer = SDL.SDL_CreateRenderer(_sdlWindow, -1, SDL.SDL_RendererFlags.SDL_RENDERER_SOFTWARE);

                    if (_sdlRenderer == IntPtr.Zero)
                    {
                        // Still no luck.
                        throw new InvalidOperationException("SDL_CreateRenderer failed.");
                    }
                }
            }

            CreateDisplayTexture(false);

            SDL.SDL_SetRenderDrawColor(_sdlRenderer, 0x00, 0x00, 0x00, 0xff);

            // Register a User event for rendering.
            _renderEventType  = SDL.SDL_RegisterEvents(1);
            _renderEvent      = new SDL.SDL_Event();
            _renderEvent.type = (SDL.SDL_EventType)_renderEventType;

            //
            // Initialize SDL Audio:
            // I'd prefer to do this in the Beeper class but there's some undocumented
            // dependency on having an active SDL window, so we do it here to keep
            // things simple.
            //
            SDL.SDL_AudioSpec desired  = new SDL.SDL_AudioSpec();
            SDL.SDL_AudioSpec obtained = new SDL.SDL_AudioSpec();

            _audioCallback = _system.IOP.Beeper.AudioCallback;

            desired.freq     = 44100;
            desired.format   = SDL.AUDIO_U8;
            desired.channels = 1;
            desired.callback = _audioCallback;
            desired.samples  = 1024;

            uint deviceId = SDL.SDL_OpenAudioDevice(null, 0, ref desired, out obtained, 0);

            SDL.SDL_PauseAudioDevice(deviceId, 0);

            if (Log.Enabled)
            {
                Log.Write(LogComponent.Beeper, "SDL Audio initialized, device id {0}", deviceId);
            }
        }
Пример #23
0
        public MyChip8()
        {
            SDLUtil sdlUtil = new SDLUtil();

            cpu.Inicializar();

            //load("PONG");
            load("C:\\Users\\Usuario\\Downloads\\CHIP-8-v.1.2-win64\\games\\roms\\VBRIX");

            bool termina    = false;
            uint last_ticks = 0;
            uint cycles     = 0;

            bool detener = false;

            // Inicializo el sonido
            SDL.SDL_AudioSpec audioSpec = sonido.Inicializar(cpu);
            SDL.SDL_OpenAudio(ref audioSpec, IntPtr.Zero);

            // Bucle principal
            while (!termina)
            {
                // Administra el teclado
                while (SDL.SDL_PollEvent(out sdlUtil.sdlEvent) != 0)
                {
                    if (sdlUtil.sdlEvent.type == SDL.SDL_EventType.SDL_QUIT)
                    {
                        termina = true;
                        break;
                    }
                    else if (sdlUtil.sdlEvent.type == SDL.SDL_EventType.SDL_KEYDOWN)
                    {
                        var key = KeyCodeToKey((int)sdlUtil.sdlEvent.key.keysym.sym);
                        cpu.keyboard.keyboard |= (ushort)(1 << key);

                        // **********************************************************
                        // Verifica tecla de "Pausa" --> No pertenece al CHIP 8!!!
                        if (key.ToString() == "25")
                        {
                            detener = true;
                        }
                        else
                        {
                            detener = false;
                        }
                        // **********************************************************

                        if (cpu.WaitingForKeyPress)
                        {
                            cpu.KeyPressed((byte)key);
                        }
                    }
                    else if (sdlUtil.sdlEvent.type == SDL.SDL_EventType.SDL_KEYUP)
                    {
                        var key = KeyCodeToKey((int)sdlUtil.sdlEvent.key.keysym.sym);
                        cpu.keyboard.keyboard &= (ushort)~(1 << key);
                    }
                }

                // Ejecuta un ciclo
                if (SDL_GetTicks() - cycles > 1)
                {
                    // Sólo se puede ejecutar un ciclo si no estamos esperando que el usuario pulse una tecla
                    if (!cpu.WaitingForKeyPress && !detener)
                    {
                        cpu.EmularCiclo();
                    }
                    cycles = SDL_GetTicks();
                }

                // Actualizo un fotograma cada luego de 60 ticks por segundo (60 instrucciones x segundo)
                // y actualizo los timers
                if ((SDL.SDL_GetTicks() - last_ticks > (1000 / 60)) && !detener)
                {
                    // Update timers
                    if (cpu.delay_timer > 0)
                    {
                        --cpu.delay_timer;
                    }

                    if (cpu.sound_timer > 0)
                    {
                        if (cpu.sound_timer > 0)
                        {
                            SDL.SDL_PauseAudio(0);
                        }
                        else //if (cpu.sound_timer == 0)
                        {
                            SDL.SDL_PauseAudio(1);
                        }
                        --cpu.sound_timer;
                    }

                    sdlUtil.Render(cpu);

                    last_ticks = SDL.SDL_GetTicks();
                }
            }

            // Finalizo
            sdlUtil.Destroy();
        }