示例#1
0
static int
prepare_audiounit(_THIS, const char *devname, int iscapture,
                  const AudioStreamBasicDescription * strdesc)
{
    OSStatus result = noErr;
    AURenderCallbackStruct callback;
#if MACOSX_COREAUDIO
    ComponentDescription desc;
    Component comp = NULL;
#else
    AudioComponentDescription desc;
    AudioComponent comp = NULL;
#endif
    const AudioUnitElement output_bus = 0;
    const AudioUnitElement input_bus = 1;
    const AudioUnitElement bus = ((iscapture) ? input_bus : output_bus);
    const AudioUnitScope scope = ((iscapture) ? kAudioUnitScope_Output :
                                  kAudioUnitScope_Input);

#if MACOSX_COREAUDIO
    if (!find_device_by_name(this, devname, iscapture)) {
        SDL_SetError("Couldn't find requested CoreAudio device");
        return 0;
    }
#endif

    SDL_zero(desc);
    desc.componentType = kAudioUnitType_Output;
    desc.componentManufacturer = kAudioUnitManufacturer_Apple;

#if MACOSX_COREAUDIO
    if (!iscapture) {
        desc.componentSubType = kAudioUnitSubType_DefaultOutput;
    } else {
        desc.componentSubType = kAudioUnitSubType_HALOutput;
    }
    comp = FindNextComponent(NULL, &desc);
#else
    desc.componentSubType = kAudioUnitSubType_RemoteIO;
    comp = AudioComponentFindNext(NULL, &desc);
#endif

    if (comp == NULL) {
        SDL_SetError("Couldn't find requested CoreAudio component");
        return 0;
    }

    /* Open & initialize the audio unit */
#if MACOSX_COREAUDIO
    result = OpenAComponent(comp, &this->hidden->audioUnit);
    CHECK_RESULT("OpenAComponent");
#else
    /*
       AudioComponentInstanceNew only available on iPhone OS 2.0 and Mac OS X 10.6
       We can't use OpenAComponent on iPhone because it is not present
     */
    result = AudioComponentInstanceNew(comp, &this->hidden->audioUnit);
    CHECK_RESULT("AudioComponentInstanceNew");
#endif

    this->hidden->audioUnitOpened = 1;

#if MACOSX_COREAUDIO
    if (iscapture) {
        UInt32 enableIO = 1;
        result = AudioUnitSetProperty(this->hidden->audioUnit,
                kAudioOutputUnitProperty_EnableIO,
                kAudioUnitScope_Input,
                input_bus,
                &enableIO, sizeof(enableIO));
        CHECK_RESULT("AudioUnitSetProperty (kAudioOutputUnitProperty_EnableIO 1)");
        enableIO = 0;
        result = AudioUnitSetProperty(this->hidden->audioUnit,
                kAudioOutputUnitProperty_EnableIO,
                kAudioUnitScope_Output,
                output_bus,
                &enableIO, sizeof(enableIO));
        CHECK_RESULT("AudioUnitSetProperty (kAudioOutputUnitProperty_EnableIO 0)");
 
        result = AudioUnitSetProperty(this->hidden->audioUnit,
                             kAudioOutputUnitProperty_CurrentDevice,
                             kAudioUnitScope_Global, 1,
                             &this->hidden->deviceID,
                             sizeof(AudioDeviceID));
        CHECK_RESULT("AudioUnitSetProperty (kAudioOutputUnitProperty_CurrentDevice)");
    } else {
        result = AudioUnitSetProperty(this->hidden->audioUnit,
                                      kAudioOutputUnitProperty_CurrentDevice,
                                      kAudioUnitScope_Global, 0,
                                      &this->hidden->deviceID,
                                      sizeof(AudioDeviceID));
        CHECK_RESULT
            ("AudioUnitSetProperty (kAudioOutputUnitProperty_CurrentDevice)");
    }
#endif

    /* Set the data format of the audio unit. */
    result = AudioUnitSetProperty(this->hidden->audioUnit,
                                  kAudioUnitProperty_StreamFormat,
                                  scope, bus, strdesc, sizeof(*strdesc));
    CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)");

    /* Set the audio callback */
    SDL_memset(&callback, 0, sizeof(AURenderCallbackStruct));
    callback.inputProc = ((iscapture) ? inputCallback : outputCallback);
    callback.inputProcRefCon = this;
    if (!iscapture) {
        result = AudioUnitSetProperty(this->hidden->audioUnit,
                                      kAudioUnitProperty_SetRenderCallback,
                                      scope, bus, &callback, sizeof(callback));
        CHECK_RESULT
            ("AudioUnitSetProperty (kAudioUnitProperty_SetRenderCallback)");
    } else {
        result = AudioUnitSetProperty(this->hidden->audioUnit,
                                      kAudioOutputUnitProperty_SetInputCallback,
                                      kAudioUnitScope_Global, bus, &callback, sizeof(callback));
        CHECK_RESULT
            ("AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)");
    }

    /* Calculate the final parameters for this audio specification */
    SDL_CalculateAudioSpec(&this->spec);

    /* Allocate a sample buffer */
    this->hidden->bufferOffset = this->hidden->bufferSize = this->spec.size;
    this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
    if (iscapture) {
        this->hidden->bufferOffset = 0;
    }

    result = AudioUnitInitialize(this->hidden->audioUnit);
    CHECK_RESULT("AudioUnitInitialize");

    /* Finally, start processing of the audio unit */
    result = AudioOutputUnitStart(this->hidden->audioUnit);
    CHECK_RESULT("AudioOutputUnitStart");

    /* We're running! */
    return 1;
}
示例#2
0
static int
GLES_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    GLES_RenderData *renderdata = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *data;
    GLint internalFormat;
    GLenum format, type;
    int texture_w, texture_h;
    GLenum result;

    switch (texture->format) {
    case SDL_PIXELFORMAT_BGR24:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_BYTE;
        break;
#ifdef ANDROID
    case SDL_PIXELFORMAT_ABGR8888:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_BYTE;
        break;
    case SDL_PIXELFORMAT_BGR565:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_SHORT_5_6_5;
        break;
    case SDL_PIXELFORMAT_ABGR1555:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_SHORT_5_5_5_1;
        break;
    case SDL_PIXELFORMAT_ABGR4444:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_SHORT_4_4_4_4;
        break;

    case SDL_PIXELFORMAT_RGB565:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_SHORT_5_6_5;
        break;
#endif
    default:
        SDL_SetError("Unsupported by OpenGL ES texture format");
        return -1;
    }

    data = (GLES_TextureData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        SDL_OutOfMemory();
        return -1;
    }

    if (texture->access == SDL_TEXTUREACCESS_STREAMING) {
        data->pitch = texture->w * SDL_BYTESPERPIXEL(texture->format);
        data->pixels = SDL_malloc(texture->h * data->pitch);
        if (!data->pixels) {
            SDL_OutOfMemory();
            SDL_free(data);
            return -1;
        }
    }

    texture->driverdata = data;

    renderdata->glGetError();
    renderdata->glEnable(GL_TEXTURE_2D);
    renderdata->glGenTextures(1, &data->texture);

    data->type = GL_TEXTURE_2D;
    /* no NPOV textures allowed in OpenGL ES (yet) */
    texture_w = power_of_2(texture->w);
    texture_h = power_of_2(texture->h);
    data->texw = (GLfloat) texture->w / texture_w;
    data->texh = (GLfloat) texture->h / texture_h;

    data->format = format;
    data->formattype = type;
    renderdata->glBindTexture(data->type, data->texture);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER,
                                GL_NEAREST);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER,
                                GL_NEAREST);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S,
                                GL_CLAMP_TO_EDGE);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T,
                                GL_CLAMP_TO_EDGE);

    renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w,
                             texture_h, 0, format, type, NULL);
    renderdata->glDisable(GL_TEXTURE_2D);

    result = renderdata->glGetError();
    if (result != GL_NO_ERROR) {
        GLES_SetError("glTexImage2D()", result);
        return -1;
    }
    return 0;
}
static int
GLES_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture)
{
    GLES_RenderData *renderdata = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *data;
    GLint internalFormat;
    GLenum format, type;
    int texture_w, texture_h;
    GLenum result;

    switch (texture->format) {
    case SDL_PIXELFORMAT_RGB24:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_BYTE;
        break;
    case SDL_PIXELFORMAT_BGR888:
    case SDL_PIXELFORMAT_ABGR8888:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_BYTE;
        break;
    case SDL_PIXELFORMAT_RGB565:
        internalFormat = GL_RGB;
        format = GL_RGB;
        type = GL_UNSIGNED_SHORT_5_6_5;
        break;
    case SDL_PIXELFORMAT_RGBA5551:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_SHORT_5_5_5_1;
        break;
    case SDL_PIXELFORMAT_RGBA4444:
        internalFormat = GL_RGBA;
        format = GL_RGBA;
        type = GL_UNSIGNED_SHORT_4_4_4_4;
        break;
    default:
        SDL_SetError("Texture format %s not supported by OpenGL ES",
                     SDL_GetPixelFormatName(texture->format));
        return -1;
    }

    data = (GLES_TextureData *) SDL_calloc(1, sizeof(*data));
    if (!data) {
        SDL_OutOfMemory();
        return -1;
    }

    if (texture->access == SDL_TEXTUREACCESS_STREAMING) 
    {
        data->pitch = texture->w * SDL_BYTESPERPIXEL(texture->format);
        data->pixels = SDL_malloc(texture->h * data->pitch);
        if (!data->pixels) {
            SDL_OutOfMemory();
            SDL_free(data);
            return -1;
        }
    }

    texture->driverdata = data;

    renderdata->glGetError();
    renderdata->glEnable(GL_TEXTURE_2D);
    renderdata->glGenTextures(1, &data->texture);

    data->type = GL_TEXTURE_2D;
    /* no NPOV textures allowed in OpenGL ES (yet) */
    texture_w = power_of_2(texture->w);
    texture_h = power_of_2(texture->h);
    data->texw = (GLfloat) texture->w / texture_w;
    data->texh = (GLfloat) texture->h / texture_h;
    if( renderer->info.max_texture_width < texture_w || renderer->info.max_texture_height < texture_h )
        __android_log_print(ANDROID_LOG_WARN, "libSDL", "GLES: Allocated texture of size %dx%d which is bigger than largest possible device texture %dx%d",
                            texture_w, texture_h, renderer->info.max_texture_width, renderer->info.max_texture_height );
    else if( texture_w > 1024 || texture_h > 1024 )
        __android_log_print(ANDROID_LOG_WARN, "libSDL", "GLES: Allocated texture of size %dx%d which is bigger than 1024x1024 - this code will not work on HTC G1", texture_w, texture_h );

    data->format = format;
    data->formattype = type;
    renderdata->glBindTexture(data->type, data->texture);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MIN_FILTER,
                                GL_NEAREST);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_MAG_FILTER,
                                GL_NEAREST);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_S,
                                GL_CLAMP_TO_EDGE);
    renderdata->glTexParameteri(data->type, GL_TEXTURE_WRAP_T,
                                GL_CLAMP_TO_EDGE);

    renderdata->glTexImage2D(data->type, 0, internalFormat, texture_w,
                             texture_h, 0, format, type, NULL);
    renderdata->glDisable(GL_TEXTURE_2D);

    result = renderdata->glGetError();
    if (result != GL_NO_ERROR) {
        GLES_SetError("glTexImage2D()", result);
        return -1;
    }
    return 0;
}
示例#4
0
SDL_bool
WatchGameController(SDL_GameController * gamecontroller)
{
    const char *name = SDL_GameControllerName(gamecontroller);
    const char *basetitle = "Game Controller Test: ";
    const size_t titlelen = SDL_strlen(basetitle) + SDL_strlen(name) + 1;
    char *title = (char *)SDL_malloc(titlelen);
    SDL_Window *window = NULL;
    SDL_Renderer *screen = NULL;
    SDL_bool retval = SDL_FALSE;
    SDL_bool done = SDL_FALSE;
    SDL_Event event;
    int i;

    if (title) {
        SDL_snprintf(title, titlelen, "%s%s", basetitle, name);
    }

    /* Create a window to display controller axis position */
    window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH,
                              SCREEN_HEIGHT, 0);
    if (window == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
        return SDL_FALSE;
    }

    screen = SDL_CreateRenderer(window, -1, 0);
    if (screen == NULL) {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
        SDL_DestroyWindow(window);
        return SDL_FALSE;
    }

    SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
    SDL_RenderClear(screen);
    SDL_RenderPresent(screen);
    SDL_RaiseWindow(window);

    /* Print info about the controller we are watching */
    SDL_Log("Watching controller %s\n",  name ? name : "Unknown Controller");

    /* Loop, getting controller events! */
    while (!done) {
        /* blank screen, set up for drawing this frame. */
        SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
        SDL_RenderClear(screen);

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_CONTROLLERAXISMOTION:
                SDL_Log("Controller %d axis %d ('%s') value: %d\n",
                       event.caxis.which,
                       event.caxis.axis,
                       ControllerAxisName((SDL_GameControllerAxis)event.caxis.axis),
                       event.caxis.value);
                break;
            case SDL_CONTROLLERBUTTONDOWN:
                SDL_Log("Controller %d button %d ('%s') down\n",
                       event.cbutton.which, event.cbutton.button,
                       ControllerButtonName((SDL_GameControllerButton)event.cbutton.button));
                break;
            case SDL_CONTROLLERBUTTONUP:
                SDL_Log("Controller %d button %d ('%s') up\n",
                       event.cbutton.which, event.cbutton.button,
                       ControllerButtonName((SDL_GameControllerButton)event.cbutton.button));
                break;
            case SDL_KEYDOWN:
                if (event.key.keysym.sym != SDLK_ESCAPE) {
                    break;
                }
                /* Fall through to signal quit */
            case SDL_QUIT:
                done = SDL_TRUE;
                break;
            default:
                break;
            }
        }
        /* Update visual controller state */
        SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE);
        for (i = 0; i <SDL_CONTROLLER_BUTTON_MAX; ++i) {
            if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
                DrawRect(screen, i * 34, SCREEN_HEIGHT - 34, 32, 32);
            }
        }

        SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE);
        for (i = 0; i < SDL_CONTROLLER_AXIS_MAX / 2; ++i) {
            /* Draw the X/Y axis */
            int x, y;
            x = (((int) SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i * 2 + 0))) + 32768);
            x *= SCREEN_WIDTH;
            x /= 65535;
            if (x < 0) {
                x = 0;
            } else if (x > (SCREEN_WIDTH - 16)) {
                x = SCREEN_WIDTH - 16;
            }
            y = (((int) SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i * 2 + 1))) + 32768);
            y *= SCREEN_HEIGHT;
            y /= 65535;
            if (y < 0) {
                y = 0;
            } else if (y > (SCREEN_HEIGHT - 16)) {
                y = SCREEN_HEIGHT - 16;
            }

            DrawRect(screen, x, y, 16, 16);
        }

        SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0xFF, SDL_ALPHA_OPAQUE);

        SDL_RenderPresent(screen);

        if (!SDL_GameControllerGetAttached(gamecontroller)) {
            done = SDL_TRUE;
            retval = SDL_TRUE;  /* keep going, wait for reattach. */
        }
    }

    SDL_DestroyRenderer(screen);
    SDL_DestroyWindow(window);
    return retval;
}
示例#5
0
/* Call to render the next GL frame */
extern void JAVA_EXPORT_NAME(DemoRenderer_nativeRender)(JNIEnv* env, jobject thiz) {
	// Set up an array of values to use as the sprite vertices.
	static GLfloat vertices[] = { 0, 0, 1, 0, 0, 1, 1, 1, };

	// Set up an array of values for the texture coordinates.
	static GLfloat texcoords[] = { 0, 0, 1, 0, 0, 1, 1, 1, };

	static GLint texcoordsCrop[] = { 0, 0, 0, 0, };

	static float clearColor = 0.0f;
	static int clearColorDir = 1;
	int textX, textY;
	void * memBufferTemp;

	if (memBuffer && openglInitialized != GL_State_Uninit2) {
		if (openglInitialized == GL_State_Init) {

			__android_log_print(ANDROID_LOG_INFO, "libSDL", " sWindowWidth=%i, sWindowHeight=%i, memX=%i, memY=%i", sWindowWidth,
					sWindowHeight, memX, memY);

			openglInitialized = GL_State_Ready;

			// Texture sizes should be 2^n
			textX = memX;
			textY = memY;

			if (textX <= 256)
				textX = 256;
			else if (textX <= 512)
				textX = 512;
			else
				textX = 1024;

			if (textY <= 256)
				textY = 256;
			else if (textY <= 512)
				textY = 512;
			else
				textY = 1024;

			//glViewport(0, 0, textX, textY);
			glViewport(0, 0, sWindowWidth, sWindowHeight);

			glClearColor(0, 0, 0, 0);
			// Set projection
			glMatrixMode(GL_PROJECTION);
			glLoadIdentity();
#if defined(GL_VERSION_ES_CM_1_0)
#define glOrtho glOrthof
#endif
			glOrtho(0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f);
			//glOrthof(0.0f, sWindowWidth, sWindowHeight, 0.0f, -1.0f, 1.0f);

			// Now Initialize modelview matrix
			glMatrixMode(GL_MODELVIEW);
			glLoadIdentity();

			glDisable(GL_DEPTH_TEST);
			glDisable(GL_CULL_FACE);
			glDisable(GL_DITHER);
			glDisable(GL_MULTISAMPLE);

			glEnable(GL_TEXTURE_2D);

			glGenTextures(1, &texture);

			glBindTexture(GL_TEXTURE_2D, texture);

			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

			glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

			void * textBuffer = SDL_malloc(textX * textY * 2);
			SDL_memset(textBuffer, 0, textX * textY * 2);

			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, textX, textY, 0, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textBuffer);

			glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

			glEnableClientState(GL_VERTEX_ARRAY);
			glEnableClientState(GL_TEXTURE_COORD_ARRAY);

			// Make the texture fit the device screen if required
			if (autoResizingActivated) {
				GLfloat ratioX = 1.0f;
				GLfloat ratioY = 1.0f;
				//if (memX > sWindowWidth) {
					ratioX = ((GLfloat) memX) / ((GLfloat) textX);
				//}
				//if (memY > sWindowHeight) {
					ratioY = ((GLfloat) memY) / ((GLfloat) textY);
				//}
				texcoords[0] *= ratioX;
				texcoords[1] *= ratioY;
				texcoords[2] *= ratioX;
				texcoords[3] *= ratioY;
				texcoords[4] *= ratioX;
				texcoords[5] *= ratioY;
				texcoords[6] *= ratioX;
				texcoords[7] *= ratioY;
				//__android_log_print(ANDROID_LOG_INFO, "libSDL", "textX=%i textY=%i, ratioX=%f ratioY=%f", textX, textY, ratioX , ratioY);
			}

			glVertexPointer(2, GL_FLOAT, 0, vertices);
			glTexCoordPointer(2, GL_FLOAT, 0, texcoords);

			glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

			// GLES extension (should be faster)
			//			texcoordsCrop[0] = 0;
			//			texcoordsCrop[1] = memY;
			//			texcoordsCrop[2] = memX;
			//			texcoordsCrop[3] = -memY;
			//			glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES, texcoordsCrop);

			glFinish();

			SDL_free(textBuffer);
		} else if (openglInitialized == GL_State_Uninit) {
			openglInitialized = GL_State_Uninit2;

			glDisableClientState(GL_TEXTURE_COORD_ARRAY);
			glDisableClientState(GL_VERTEX_ARRAY);

			glDeleteTextures(1, &texture);

			return;
		}

//		if (WaitForNativeRender) {
//			SDL_mutexP(WaitForNativeRender);
//
//			WaitForNativeRenderState = Render_State_Finished;
//			SDL_CondSignal(WaitForNativeRender1);
//
//			while (WaitForNativeRenderState != Render_State_Started) {
//				if (SDL_CondWaitTimeout(WaitForNativeRender1, WaitForNativeRender, 1000) != 0) {
//					__android_log_print(ANDROID_LOG_INFO, "libSDL", "Frame failed to render");
//					SDL_mutexV(WaitForNativeRender);
//					return;
//				}
//			}
//
//			memBufferTemp = memBuffer;
//
//			WaitForNativeRenderState = Render_State_Processing;
//
//			SDL_CondSignal(WaitForNativeRender1);
//
//			SDL_mutexV(WaitForNativeRender);
//		} else {
			memBufferTemp = memBuffer;
//		}

		glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, memX, memY, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, memBufferTemp);

		//glClearColor(0, 1.0f, 0, 1.0f);
		//glClear(GL_COLOR_BUFFER_BIT);

		glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
//		glDrawTexiOES(0, sWindowHeight-memY, 1, memX, memY); // GLES extension (should be faster)
		//__android_log_print(ANDROID_LOG_INFO, "libSDL", "glDrawTexiOES(%i, 1, %i, %i)", sWindowHeight-memY ,memX, memY);
		glFinish(); //glFlush();

	} else {
		/*
		 // Flash the screen
		 if( clearColor >= 1.0f )
		 clearColorDir = -1;
		 else if( clearColor <= 0.0f )
		 clearColorDir = 1;

		 clearColor += (float)clearColorDir * 0.01f;
		 glClearColor(clearColor,clearColor,clearColor,0);
		 glClear(GL_COLOR_BUFFER_BIT);
		 SDL_Delay(50);
		 */
	}
}
示例#6
0
static int
NETBSDAUDIO_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
{
    const int flags = iscapture ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT;
    SDL_AudioFormat format = 0;
    audio_info_t info;
    audio_prinfo *prinfo = iscapture ? &info.play : &info.record;

    /* We don't care what the devname is...we'll try to open anything. */
    /*  ...but default to first name in the list... */
    if (devname == NULL) {
        devname = SDL_GetAudioDeviceName(0, iscapture);
        if (devname == NULL) {
            return SDL_SetError("No such audio device");
        }
    }

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        return SDL_OutOfMemory();
    }
    SDL_zerop(this->hidden);

    /* Open the audio device */
    this->hidden->audio_fd = open(devname, flags, 0);
    if (this->hidden->audio_fd < 0) {
        return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno));
    }

    AUDIO_INITINFO(&info);

    /* Calculate the final parameters for this audio specification */
    SDL_CalculateAudioSpec(&this->spec);

    /* Set to play mode */
    info.mode = iscapture ? AUMODE_RECORD : AUMODE_PLAY;
    if (ioctl(this->hidden->audio_fd, AUDIO_SETINFO, &info) < 0) {
        return SDL_SetError("Couldn't put device into play mode");
    }

    AUDIO_INITINFO(&info);
    for (format = SDL_FirstAudioFormat(this->spec.format);
         format; format = SDL_NextAudioFormat()) {
        switch (format) {
        case AUDIO_U8:
            prinfo->encoding = AUDIO_ENCODING_ULINEAR;
            prinfo->precision = 8;
            break;
        case AUDIO_S8:
            prinfo->encoding = AUDIO_ENCODING_SLINEAR;
            prinfo->precision = 8;
            break;
        case AUDIO_S16LSB:
            prinfo->encoding = AUDIO_ENCODING_SLINEAR_LE;
            prinfo->precision = 16;
            break;
        case AUDIO_S16MSB:
            prinfo->encoding = AUDIO_ENCODING_SLINEAR_BE;
            prinfo->precision = 16;
            break;
        case AUDIO_U16LSB:
            prinfo->encoding = AUDIO_ENCODING_ULINEAR_LE;
            prinfo->precision = 16;
            break;
        case AUDIO_U16MSB:
            prinfo->encoding = AUDIO_ENCODING_ULINEAR_BE;
            prinfo->precision = 16;
            break;
        default:
            continue;
        }

        if (ioctl(this->hidden->audio_fd, AUDIO_SETINFO, &info) == 0) {
            break;
        }
    }

    if (!format) {
        return SDL_SetError("No supported encoding for 0x%x", this->spec.format);
    }

    this->spec.format = format;

    AUDIO_INITINFO(&info);
    prinfo->channels = this->spec.channels;
    if (ioctl(this->hidden->audio_fd, AUDIO_SETINFO, &info) == -1) {
        this->spec.channels = 1;
    }
    AUDIO_INITINFO(&info);
    prinfo->sample_rate = this->spec.freq;
    info.blocksize = this->spec.size;
    info.hiwat = 5;
    info.lowat = 3;
    (void) ioctl(this->hidden->audio_fd, AUDIO_SETINFO, &info);
    (void) ioctl(this->hidden->audio_fd, AUDIO_GETINFO, &info);
    this->spec.freq = prinfo->sample_rate;

    if (!iscapture) {
        /* Allocate mixing buffer */
        this->hidden->mixlen = this->spec.size;
        this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen);
        if (this->hidden->mixbuf == NULL) {
            return SDL_OutOfMemory();
        }
        SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
    }

    NETBSDAUDIO_Status(this);

    /* We're ready to rock and roll. :-) */
    return 0;
}
示例#7
0
int NX_VideoInit (_THIS, SDL_PixelFormat * vformat)
{
    GR_SCREEN_INFO si ;

    Dprintf ("enter NX_VideoInit\n") ;
    
    if (GrOpen () < 0) {
        SDL_SetError ("GrOpen() fail") ;
        return -1 ;
    }

    // use share memory to speed up
#ifdef NANOX_SHARE_MEMORY
    GrReqShmCmds (0xFFFF);
#endif

    SDL_Window = 0 ;
    FSwindow = 0 ;

    GammaRamp_R = NULL ;
    GammaRamp_G = NULL ;
    GammaRamp_B = NULL ;    

    GrGetScreenInfo (& si) ;
    SDL_Visual.bpp = si.bpp ;

    /* Determine the current screen size */
    this->info.current_w = si.cols ;
    this->info.current_h = si.rows ;

    // GetVideoMode
    SDL_modelist = (SDL_Rect **) SDL_malloc (sizeof (SDL_Rect *) * 2) ;
    if (SDL_modelist) {
        SDL_modelist [0] = (SDL_Rect *) SDL_malloc (sizeof(SDL_Rect)) ;
        if (SDL_modelist [0]) {
            SDL_modelist [0] -> x = 0 ;
            SDL_modelist [0] -> y = 0 ;
            SDL_modelist [0] -> w = si.cols ;
            SDL_modelist [0] -> h = si.rows ;
        }
        SDL_modelist [1] = NULL ;
    }

    pixel_type = si.pixtype;
    SDL_Visual.red_mask = si.rmask;
    SDL_Visual.green_mask = si.gmask;
    SDL_Visual.blue_mask = si.bmask;

    vformat -> BitsPerPixel = SDL_Visual.bpp ;
    if (vformat -> BitsPerPixel > 8) {
        vformat -> Rmask = SDL_Visual.red_mask ;
        vformat -> Gmask = SDL_Visual.green_mask ;
        vformat -> Bmask = SDL_Visual.blue_mask ;
    }

    // See if we have been passed a window to use
    SDL_windowid = getenv ("SDL_WINDOWID") ;
    
    // Create the fullscreen (and managed windows : no implement)
    create_aux_windows (this) ;

    Dprintf ("leave NX_VideoInit\n") ;
    return 0 ;
}
示例#8
0
static char *
GetJoystickName(int index, const char *szRegKey)
{
    /* added 7/24/2004 by Eckhard Stolberg */
    /*
       see if there is a joystick for the current
       index (1-16) listed in the registry
     */
    char *name = NULL;
    HKEY hTopKey;
    HKEY hKey;
    DWORD regsize;
    LONG regresult;
    char regkey[256];
    char regvalue[256];
    char regname[256];

    SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s\\%s",
                 REGSTR_PATH_JOYCONFIG, szRegKey, REGSTR_KEY_JOYCURR);
    hTopKey = HKEY_LOCAL_MACHINE;
    regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
    if (regresult != ERROR_SUCCESS) {
        hTopKey = HKEY_CURRENT_USER;
        regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
    }
    if (regresult != ERROR_SUCCESS) {
        return NULL;
    }

    /* find the registry key name for the joystick's properties */
    regsize = sizeof(regname);
    SDL_snprintf(regvalue, SDL_arraysize(regvalue), "Joystick%d%s", index + 1,
                 REGSTR_VAL_JOYOEMNAME);
    regresult =
        RegQueryValueExA(hKey, regvalue, 0, 0, (LPBYTE) regname, &regsize);
    RegCloseKey(hKey);

    if (regresult != ERROR_SUCCESS) {
        return NULL;
    }

    /* open that registry key */
    SDL_snprintf(regkey, SDL_arraysize(regkey), "%s\\%s", REGSTR_PATH_JOYOEM,
                 regname);
    regresult = RegOpenKeyExA(hTopKey, regkey, 0, KEY_READ, &hKey);
    if (regresult != ERROR_SUCCESS) {
        return NULL;
    }

    /* find the size for the OEM name text */
    regsize = sizeof(regvalue);
    regresult =
        RegQueryValueExA(hKey, REGSTR_VAL_JOYOEMNAME, 0, 0, NULL, &regsize);
    if (regresult == ERROR_SUCCESS) {
        /* allocate enough memory for the OEM name text ... */
        name = (char *) SDL_malloc(regsize);
        if (name) {
            /* ... and read it from the registry */
            regresult = RegQueryValueExA(hKey,
                                         REGSTR_VAL_JOYOEMNAME, 0, 0,
                                         (LPBYTE) name, &regsize);
        }
    }
    RegCloseKey(hKey);

    return (name);
}
示例#9
0
static BOOL VManQueryVideoModes(SDL_PrivateVideoData *pPVData)
{
  ULONG			ulRC;
  GDDMODEINFO		sCurModeInfo;
  VMIQCI		sVmiQCI;
  CHAININFO		*pChainInfo;
  PGRADDINFO		pGraddInfo;
  GDDMODEINFO		*pModeInfo;
  ULONG			ulIdx;
  PVIDEOMODE		pVideoMode;

  SDL_Rect		**ppSDLRectList;
  ULONG			ulRectIdx;
  LONG			lPos;
  static ULONG		aModeItemBPP[OS2VMAN_FSMODELIST_SIZE] = {15,8,16,24,32};

  // Query avaible video modes from VMAN, fill pVideoModes, detect current mode

  ulRC = pfnVMIEntry( 0, VMI_CMD_QUERYCURRENTMODE, NULL, &sCurModeInfo );
  if ( ulRC != RC_SUCCESS )
  {
    SDL_SetError( "Could not query desktop video mode." );
    return FALSE;
  }

  sVmiQCI.ulLength = sizeof(VMIQCI);
  ulRC = pfnVMIEntry( 0, VMI_CMD_QUERYCHAININFO, NULL, &sVmiQCI );
  if ( ulRC != RC_SUCCESS )
  {
    SDL_SetError( "pfnVMIEntry(,VMI_CMD_QUERYCHAININFO,,), rc = %u", ulRC );
    return FALSE;
  }

  for( pChainInfo = sVmiQCI.pciHead; pChainInfo != NULL;
       pChainInfo = pChainInfo->pNextChainInfo )
  {
    for( pGraddInfo = pChainInfo->pGraddList; pGraddInfo != NULL;
         pGraddInfo = pGraddInfo->pNextGraddInfo )
    {
      pModeInfo = pGraddInfo->pModeInfo;

      for( ulIdx = 0; ulIdx < pGraddInfo->cModes; ulIdx++,
           pModeInfo = (GDDMODEINFO *)&((PCHAR)pModeInfo)[pModeInfo->ulLength] )
      {
        if ( pModeInfo->ulBpp == 16 && pModeInfo->cColors == 32768 )
          pModeInfo->ulBpp = 15;

        debug( "Mode %X %ux%u, BPP: %u (%.4s), colors: %d%s%s",
               pModeInfo->ulModeId, pModeInfo->ulHorizResolution,
               pModeInfo->ulVertResolution, pModeInfo->ulBpp,
               &pModeInfo->fccColorEncoding, pModeInfo->cColors,
               pModeInfo->ulModeId == sCurModeInfo.ulModeId ? " - CURRENT" : "",
               /*pModeInfo->ulBpp <= 8 ? " - IGNORED" : */"" );

        // if ( pModeInfo->ulBpp <= 8 )
        //   continue;

        pVideoMode = SDL_malloc( sizeof(VIDEOMODE) );
        if ( pVideoMode == NULL )
        {
          SDL_NotEnoughMemory();
          VManFreeVideoModes( pPVData );
          return FALSE;
        }

        if ( pModeInfo->ulModeId == sCurModeInfo.ulModeId )
          pPVData->pDesktopVideoMode = pVideoMode;

        pVideoMode->uiModeID         = pModeInfo->ulModeId;
        pVideoMode->sSDLRect.x       = 0;
        pVideoMode->sSDLRect.y       = 0;
        pVideoMode->sSDLRect.w       = pModeInfo->ulHorizResolution;
        pVideoMode->sSDLRect.h       = pModeInfo->ulVertResolution;
        pVideoMode->uiBPP            = pModeInfo->ulBpp;
        pVideoMode->uiScanLineSize   = pModeInfo->ulScanLineSize;
        pVideoMode->fccColorEncoding = pModeInfo->fccColorEncoding;
        pVideoMode->pNext            = pPVData->pVideoModes;
        pPVData->pVideoModes = pVideoMode;
      }
    }
  }

  if ( pPVData->pDesktopVideoMode == NULL )
  {
    SDL_SetError( "Current video mode not found" );
    VManFreeVideoModes( pPVData );
    return FALSE;
  }

  // Sort video modes, fill pListVideoModes - it will be returned to SDL

  for( ulIdx = 0; ulIdx < OS2VMAN_FSMODELIST_SIZE; ulIdx++ )
  {
    ppSDLRectList = pPVData->pListVideoModes[ulIdx];

    for( pVideoMode = pPVData->pVideoModes; pVideoMode != NULL;
         pVideoMode = pVideoMode->pNext )
    {
      if ( pVideoMode->uiBPP != aModeItemBPP[ulIdx] )
        continue;

      if ( ppSDLRectList == NULL )
      {
        // First record in list
        ppSDLRectList = SDL_malloc( 2 * sizeof(SDL_Rect*) );
        if ( ppSDLRectList == NULL )
          continue;

        ppSDLRectList[0] = &pVideoMode->sSDLRect;
        ppSDLRectList[1] = NULL;
        pPVData->pListVideoModes[ulIdx] = ppSDLRectList;
        continue;
      }

      // Search position in sorted list, count number of items
      lPos = -1;
      for( ulRectIdx = 0; ppSDLRectList[ulRectIdx] != NULL; ulRectIdx++ )
      {
        if ( lPos != -1 ) // Position found - continue calc number of items
          continue;

        if ( ( ppSDLRectList[ulRectIdx]->w * ppSDLRectList[ulRectIdx]->h ) <
             ( pVideoMode->sSDLRect.w * pVideoMode->sSDLRect.h ) )
          lPos = ulRectIdx;
      }

      if ( lPos == -1 )
        lPos = ulRectIdx; // Position not found, get position of NULL
      ulRectIdx++;

      // Insert new item
      ppSDLRectList = SDL_realloc( ppSDLRectList,
                                   ( ulRectIdx + 1 ) * sizeof(SDL_Rect*) );
      if ( ppSDLRectList == NULL )
        continue;
      pPVData->pListVideoModes[ulIdx] = ppSDLRectList;
      SDL_memmove( &ppSDLRectList[lPos + 1], &ppSDLRectList[lPos],
                   ( ulRectIdx - lPos ) * sizeof(SDL_Rect*) );
      ppSDLRectList[lPos] = &pVideoMode->sSDLRect;
    }
  }

#ifdef DEBUG_BUILD
  // Debug. Show sorted lists
  for( ulIdx = 0; ulIdx < OS2VMAN_FSMODELIST_SIZE; ulIdx++ )
  {
    ppSDLRectList = pPVData->pListVideoModes[ulIdx];
    if ( ppSDLRectList == NULL )
      continue;
    debug( "Modes list #%u for %u BPP:", ulIdx, aModeItemBPP[ulIdx] );
    for( ulRectIdx = 0; ppSDLRectList[ulRectIdx] != NULL; ulRectIdx++ )
      debug( "  %u x %u", ppSDLRectList[ulRectIdx]->w,
                          ppSDLRectList[ulRectIdx]->h );
  }
#endif
  return TRUE;
}
示例#10
0
SDL_Surface *IMG_LoadPNM_RW(SDL_RWops *src)
{
    Sint64 start;
    SDL_Surface *surface = NULL;
    int width, height;
    int maxval, y, bpl;
    Uint8 *row;
    Uint8 *buf = NULL;
    char *error = NULL;
    Uint8 magic[2];
    int ascii;
    enum { PBM, PGM, PPM, PAM } kind;

#define ERROR(s) do { error = (s); goto done; } while(0)

    if ( !src ) {
        /* The error message has been set in SDL_RWFromFile */
        return NULL;
    }
    start = SDL_RWtell(src);

    SDL_RWread(src, magic, 2, 1);
    kind = magic[1] - '1';
    ascii = 1;
    if(kind >= 3) {
        ascii = 0;
        kind -= 3;
    }

    width = ReadNumber(src);
    height = ReadNumber(src);
    if(width <= 0 || height <= 0)
        ERROR("Unable to read image width and height");

    if(kind != PBM) {
        maxval = ReadNumber(src);
        if(maxval <= 0 || maxval > 255)
            ERROR("unsupported PNM format");
    } else
        maxval = 255;   /* never scale PBMs */

    /* binary PNM allows just a single character of whitespace after
       the last parameter, and we've already consumed it */

    if(kind == PPM) {
        /* 24-bit surface in R,G,B byte order */
        surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 24,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
                       0x000000ff, 0x0000ff00, 0x00ff0000,
#else
                       0x00ff0000, 0x0000ff00, 0x000000ff,
#endif
                       0);
    } else {
        /* load PBM/PGM as 8-bit indexed images */
        surface = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 8,
                       0, 0, 0, 0);
    }
    if ( surface == NULL )
        ERROR("Out of memory");
    bpl = width * surface->format->BytesPerPixel;
    if(kind == PGM) {
        SDL_Color *c = surface->format->palette->colors;
        int i;
        for(i = 0; i < 256; i++)
            c[i].r = c[i].g = c[i].b = i;
        surface->format->palette->ncolors = 256;
    } else if(kind == PBM) {
        /* for some reason PBM has 1=black, 0=white */
        SDL_Color *c = surface->format->palette->colors;
        c[0].r = c[0].g = c[0].b = 255;
        c[1].r = c[1].g = c[1].b = 0;
        surface->format->palette->ncolors = 2;
        bpl = (width + 7) >> 3;
        buf = (Uint8 *)SDL_malloc(bpl);
        if(buf == NULL)
            ERROR("Out of memory");
    }
示例#11
0
static int
PAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
{
    const char *workaround = SDL_getenv("SDL_DSP_NOSELECT");
    char audiodev[1024];
    const char *err = NULL;
    int format;
    int bytes_per_sample;
    SDL_AudioFormat test_format;
    audio_init paud_init;
    audio_buffer paud_bufinfo;
    audio_status paud_status;
    audio_control paud_control;
    audio_change paud_change;
    int fd = -1;

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        return SDL_OutOfMemory();
    }
    SDL_memset(this->hidden, 0, (sizeof *this->hidden));

    /* Open the audio device */
    fd = OpenAudioPath(audiodev, sizeof(audiodev), OPEN_FLAGS, 0);
    this->hidden->audio_fd = fd;
    if (fd < 0) {
        PAUDIO_CloseDevice(this);
        return SDL_SetError("Couldn't open %s: %s", audiodev, strerror(errno));
    }

    /*
     * We can't set the buffer size - just ask the device for the maximum
     * that we can have.
     */
    if (ioctl(fd, AUDIO_BUFFER, &paud_bufinfo) < 0) {
        PAUDIO_CloseDevice(this);
        return SDL_SetError("Couldn't get audio buffer information");
    }

    if (this->spec.channels > 1)
        this->spec.channels = 2;
    else
        this->spec.channels = 1;

    /*
     * Fields in the audio_init structure:
     *
     * Ignored by us:
     *
     * paud.loadpath[LOAD_PATH]; * DSP code to load, MWave chip only?
     * paud.slot_number;         * slot number of the adapter
     * paud.device_id;           * adapter identification number
     *
     * Input:
     *
     * paud.srate;           * the sampling rate in Hz
     * paud.bits_per_sample; * 8, 16, 32, ...
     * paud.bsize;           * block size for this rate
     * paud.mode;            * ADPCM, PCM, MU_LAW, A_LAW, SOURCE_MIX
     * paud.channels;        * 1=mono, 2=stereo
     * paud.flags;           * FIXED - fixed length data
     *                       * LEFT_ALIGNED, RIGHT_ALIGNED (var len only)
     *                       * TWOS_COMPLEMENT - 2's complement data
     *                       * SIGNED - signed? comment seems wrong in sys/audio.h
     *                       * BIG_ENDIAN
     * paud.operation;       * PLAY, RECORD
     *
     * Output:
     *
     * paud.flags;           * PITCH            - pitch is supported
     *                       * INPUT            - input is supported
     *                       * OUTPUT           - output is supported
     *                       * MONITOR          - monitor is supported
     *                       * VOLUME           - volume is supported
     *                       * VOLUME_DELAY     - volume delay is supported
     *                       * BALANCE          - balance is supported
     *                       * BALANCE_DELAY    - balance delay is supported
     *                       * TREBLE           - treble control is supported
     *                       * BASS             - bass control is supported
     *                       * BESTFIT_PROVIDED - best fit returned
     *                       * LOAD_CODE        - DSP load needed
     * paud.rc;              * NO_PLAY         - DSP code can't do play requests
     *                       * NO_RECORD       - DSP code can't do record requests
     *                       * INVALID_REQUEST - request was invalid
     *                       * CONFLICT        - conflict with open's flags
     *                       * OVERLOADED      - out of DSP MIPS or memory
     * paud.position_resolution; * smallest increment for position
     */

    paud_init.srate = this->spec.freq;
    paud_init.mode = PCM;
    paud_init.operation = PLAY;
    paud_init.channels = this->spec.channels;

    /* Try for a closest match on audio format */
    format = 0;
    for (test_format = SDL_FirstAudioFormat(this->spec.format);
         !format && test_format;) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
#endif
        switch (test_format) {
        case AUDIO_U8:
            bytes_per_sample = 1;
            paud_init.bits_per_sample = 8;
            paud_init.flags = TWOS_COMPLEMENT | FIXED;
            format = 1;
            break;
        case AUDIO_S8:
            bytes_per_sample = 1;
            paud_init.bits_per_sample = 8;
            paud_init.flags = SIGNED | TWOS_COMPLEMENT | FIXED;
            format = 1;
            break;
        case AUDIO_S16LSB:
            bytes_per_sample = 2;
            paud_init.bits_per_sample = 16;
            paud_init.flags = SIGNED | TWOS_COMPLEMENT | FIXED;
            format = 1;
            break;
        case AUDIO_S16MSB:
            bytes_per_sample = 2;
            paud_init.bits_per_sample = 16;
            paud_init.flags = BIG_ENDIAN | SIGNED | TWOS_COMPLEMENT | FIXED;
            format = 1;
            break;
        case AUDIO_U16LSB:
            bytes_per_sample = 2;
            paud_init.bits_per_sample = 16;
            paud_init.flags = TWOS_COMPLEMENT | FIXED;
            format = 1;
            break;
        case AUDIO_U16MSB:
            bytes_per_sample = 2;
            paud_init.bits_per_sample = 16;
            paud_init.flags = BIG_ENDIAN | TWOS_COMPLEMENT | FIXED;
            format = 1;
            break;
        default:
            break;
        }
        if (!format) {
            test_format = SDL_NextAudioFormat();
        }
    }
    if (format == 0) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Couldn't find any hardware audio formats\n");
#endif
        PAUDIO_CloseDevice(this);
        return SDL_SetError("Couldn't find any hardware audio formats");
    }
    this->spec.format = test_format;

    /*
     * We know the buffer size and the max number of subsequent writes
     *  that can be pending. If more than one can pend, allow the application
     *  to do something like double buffering between our write buffer and
     *  the device's own buffer that we are filling with write() anyway.
     *
     * We calculate this->spec.samples like this because
     *  SDL_CalculateAudioSpec() will give put paud_bufinfo.write_buf_cap
     *  (or paud_bufinfo.write_buf_cap/2) into this->spec.size in return.
     */
    if (paud_bufinfo.request_buf_cap == 1) {
        this->spec.samples = paud_bufinfo.write_buf_cap
            / bytes_per_sample / this->spec.channels;
    } else {
        this->spec.samples = paud_bufinfo.write_buf_cap
            / bytes_per_sample / this->spec.channels / 2;
    }
    paud_init.bsize = bytes_per_sample * this->spec.channels;

    SDL_CalculateAudioSpec(&this->spec);

    /*
     * The AIX paud device init can't modify the values of the audio_init
     * structure that we pass to it. So we don't need any recalculation
     * of this stuff and no reinit call as in linux dsp code.
     *
     * /dev/paud supports all of the encoding formats, so we don't need
     * to do anything like reopening the device, either.
     */
    if (ioctl(fd, AUDIO_INIT, &paud_init) < 0) {
        switch (paud_init.rc) {
        case 1:
            err = "Couldn't set audio format: DSP can't do play requests";
            break;
        case 2:
            err = "Couldn't set audio format: DSP can't do record requests";
            break;
        case 4:
            err = "Couldn't set audio format: request was invalid";
            break;
        case 5:
            err = "Couldn't set audio format: conflict with open's flags";
            break;
        case 6:
            err = "Couldn't set audio format: out of DSP MIPS or memory";
            break;
        default:
            err = "Couldn't set audio format: not documented in sys/audio.h";
            break;
        }
    }

    if (err != NULL) {
        PAUDIO_CloseDevice(this);
        return SDL_SetError("Paudio: %s", err);
    }

    /* Allocate mixing buffer */
    this->hidden->mixlen = this->spec.size;
    this->hidden->mixbuf = (Uint8 *) SDL_AllocAudioMem(this->hidden->mixlen);
    if (this->hidden->mixbuf == NULL) {
        PAUDIO_CloseDevice(this);
        return SDL_OutOfMemory();
    }
    SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);

    /*
     * Set some paramters: full volume, first speaker that we can find.
     * Ignore the other settings for now.
     */
    paud_change.input = AUDIO_IGNORE;   /* the new input source */
    paud_change.output = OUTPUT_1;      /* EXTERNAL_SPEAKER,INTERNAL_SPEAKER,OUTPUT_1 */
    paud_change.monitor = AUDIO_IGNORE; /* the new monitor state */
    paud_change.volume = 0x7fffffff;    /* volume level [0-0x7fffffff] */
    paud_change.volume_delay = AUDIO_IGNORE;    /* the new volume delay */
    paud_change.balance = 0x3fffffff;   /* the new balance */
    paud_change.balance_delay = AUDIO_IGNORE;   /* the new balance delay */
    paud_change.treble = AUDIO_IGNORE;  /* the new treble state */
    paud_change.bass = AUDIO_IGNORE;    /* the new bass state */
    paud_change.pitch = AUDIO_IGNORE;   /* the new pitch state */

    paud_control.ioctl_request = AUDIO_CHANGE;
    paud_control.request_info = (char *) &paud_change;
    if (ioctl(fd, AUDIO_CONTROL, &paud_control) < 0) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Can't change audio display settings\n");
#endif
    }

    /*
     * Tell the device to expect data. Actual start will wait for
     * the first write() call.
     */
    paud_control.ioctl_request = AUDIO_START;
    paud_control.position = 0;
    if (ioctl(fd, AUDIO_CONTROL, &paud_control) < 0) {
        PAUDIO_CloseDevice(this);
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Can't start audio play\n");
#endif
        return SDL_SetError("Can't start audio play");
    }

    /* Check to see if we need to use select() workaround */
    if (workaround != NULL) {
        this->hidden->frame_ticks = (float) (this->spec.samples * 1000) /
            this->spec.freq;
        this->hidden->next_frame = SDL_GetTicks() + this->hidden->frame_ticks;
    }

    /* We're ready to rock and roll. :-) */
    return 0;
}
示例#12
0
static int
GLES_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                   const SDL_Rect * rect, const void *pixels, int pitch)
{
    GLES_RenderData *renderdata = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *data = (GLES_TextureData *) texture->driverdata;
    Uint8 *blob = NULL;
    Uint8 *src;
    int srcPitch;
    int y;

    GLES_ActivateRenderer(renderer);

    /* Bail out if we're supposed to update an empty rectangle */
    if (rect->w <= 0 || rect->h <= 0)
        return 0;

    /* Reformat the texture data into a tightly packed array */
    srcPitch = rect->w * SDL_BYTESPERPIXEL(texture->format);
    src = (Uint8 *)pixels;
    if (pitch != srcPitch)
    {
        blob = (Uint8 *)SDL_malloc(srcPitch * rect->h);
        if (!blob)
        {
            SDL_OutOfMemory();
            return -1;
        }
        src = blob;
        for (y = 0; y < rect->h; ++y)
        {
            SDL_memcpy(src, pixels, srcPitch);
            src += srcPitch;
            pixels = (Uint8 *)pixels + pitch;
        }
        src = blob;
    }

    /* Create a texture subimage with the supplied data */
    renderdata->glGetError();
    renderdata->glEnable(data->type);
    renderdata->glBindTexture(data->type, data->texture);
    renderdata->glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    renderdata->glTexSubImage2D(data->type,
                    0,
                    rect->x,
                    rect->y,
                    rect->w,
                    rect->h,
                    data->format,
                    data->formattype,
                    src);
    if (blob) {
        SDL_free(blob);
    }

    if (renderdata->glGetError() != GL_NO_ERROR)
    {
        SDL_SetError("Failed to update texture");
        return -1;
    }
    return 0;
}
示例#13
0
static void
build_device_list(int iscapture, addDevFn addfn, void *addfndata)
{
    OSStatus result = noErr;
    UInt32 size = 0;
    AudioDeviceID *devs = NULL;
    UInt32 i = 0;
    UInt32 max = 0;

    AudioObjectPropertyAddress addr = {
        kAudioHardwarePropertyDevices,
        kAudioObjectPropertyScopeGlobal,
        kAudioObjectPropertyElementMaster
    };

    result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr,
                                            0, NULL, &size);
    if (result != kAudioHardwareNoError)
        return;

    devs = (AudioDeviceID *) alloca(size);
    if (devs == NULL)
        return;

    result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr,
                                        0, NULL, &size, devs);
    if (result != kAudioHardwareNoError)
        return;

    max = size / sizeof (AudioDeviceID);
    for (i = 0; i < max; i++) {
        CFStringRef cfstr = NULL;
        char *ptr = NULL;
        AudioDeviceID dev = devs[i];
        AudioBufferList *buflist = NULL;
        int usable = 0;
        CFIndex len = 0;

        addr.mScope = iscapture ? kAudioDevicePropertyScopeInput :
                        kAudioDevicePropertyScopeOutput;
        addr.mSelector = kAudioDevicePropertyStreamConfiguration;

        result = AudioObjectGetPropertyDataSize(dev, &addr, 0, NULL, &size);
        if (result != noErr)
            continue;

        buflist = (AudioBufferList *) SDL_malloc(size);
        if (buflist == NULL)
            continue;

        result = AudioObjectGetPropertyData(dev, &addr, 0, NULL,
                                            &size, buflist);

        if (result == noErr) {
            UInt32 j;
            for (j = 0; j < buflist->mNumberBuffers; j++) {
                if (buflist->mBuffers[j].mNumberChannels > 0) {
                    usable = 1;
                    break;
                }
            }
        }

        SDL_free(buflist);

        if (!usable)
            continue;

        addr.mSelector = kAudioObjectPropertyName;
        size = sizeof (CFStringRef);
        result = AudioObjectGetPropertyData(dev, &addr, 0, NULL, &size, &cfstr);
        if (result != kAudioHardwareNoError)
            continue;

        len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr),
                                                kCFStringEncodingUTF8);

        ptr = (char *) SDL_malloc(len + 1);
        usable = ((ptr != NULL) &&
                  (CFStringGetCString
                   (cfstr, ptr, len + 1, kCFStringEncodingUTF8)));

        CFRelease(cfstr);

        if (usable) {
            len = strlen(ptr);
            /* Some devices have whitespace at the end...trim it. */
            while ((len > 0) && (ptr[len - 1] == ' ')) {
                len--;
            }
            usable = (len > 0);
        }

        if (usable) {
            ptr[len] = '\0';

#if DEBUG_COREAUDIO
            printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n",
                   ((iscapture) ? "capture" : "output"),
                   (int) *devCount, ptr, (int) dev);
#endif
            addfn(ptr, dev, addfndata);
        }
        SDL_free(ptr);  /* addfn() would have copied the string. */
    }
}
示例#14
0
static int
COREAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
{
    AudioStreamBasicDescription strdesc;
    SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
    int valid_datatype = 0;

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        return SDL_OutOfMemory();
    }
    SDL_memset(this->hidden, 0, (sizeof *this->hidden));

    /* Setup a AudioStreamBasicDescription with the requested format */
    SDL_memset(&strdesc, '\0', sizeof(AudioStreamBasicDescription));
    strdesc.mFormatID = kAudioFormatLinearPCM;
    strdesc.mFormatFlags = kLinearPCMFormatFlagIsPacked;
    strdesc.mChannelsPerFrame = this->spec.channels;
    strdesc.mSampleRate = this->spec.freq;
    strdesc.mFramesPerPacket = 1;

    while ((!valid_datatype) && (test_format)) {
        this->spec.format = test_format;
        /* Just a list of valid SDL formats, so people don't pass junk here. */
        switch (test_format) {
        case AUDIO_U8:
        case AUDIO_S8:
        case AUDIO_U16LSB:
        case AUDIO_S16LSB:
        case AUDIO_U16MSB:
        case AUDIO_S16MSB:
        case AUDIO_S32LSB:
        case AUDIO_S32MSB:
        case AUDIO_F32LSB:
        case AUDIO_F32MSB:
            valid_datatype = 1;
            strdesc.mBitsPerChannel = SDL_AUDIO_BITSIZE(this->spec.format);
            if (SDL_AUDIO_ISBIGENDIAN(this->spec.format))
                strdesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;

            if (SDL_AUDIO_ISFLOAT(this->spec.format))
                strdesc.mFormatFlags |= kLinearPCMFormatFlagIsFloat;
            else if (SDL_AUDIO_ISSIGNED(this->spec.format))
                strdesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
            break;
        }
    }

    if (!valid_datatype) {      /* shouldn't happen, but just in case... */
        COREAUDIO_CloseDevice(this);
        return SDL_SetError("Unsupported audio format");
    }

    strdesc.mBytesPerFrame =
        strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
    strdesc.mBytesPerPacket =
        strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;

    if (!prepare_audiounit(this, devname, iscapture, &strdesc)) {
        COREAUDIO_CloseDevice(this);
        return -1;      /* prepare_audiounit() will call SDL_SetError()... */
    }

    return 0;   /* good to go. */
}
示例#15
0
/**
* \brief Execute a test suite using the given run seed and execution key.
*
* The filter string is matched to the suite name (full comparison) to select a single suite,
* or if no suite matches, it is matched to the test names (full comparison) to select a single test.
*
* \param testSuites Suites containing the test case.
* \param userRunSeed Custom run seed provided by user, or NULL to autogenerate one.
* \param userExecKey Custom execution key provided by user, or 0 to autogenerate one.
* \param filter Filter specification. NULL disables. Case sensitive.
* \param testIterations Number of iterations to run each test case.
*
* \returns Test run result; 0 when all tests passed, 1 if any tests failed.
*/
int SDLTest_RunSuites(SDLTest_TestSuiteReference *testSuites[], const char *userRunSeed, Uint64 userExecKey, const char *filter, int testIterations)
{
    int totalNumberOfTests = 0;
    int failedNumberOfTests = 0;
    int suiteCounter;
    int testCounter;
    int iterationCounter;
    SDLTest_TestSuiteReference *testSuite;
    SDLTest_TestCaseReference *testCase;
    const char *runSeed = NULL;
    char *currentSuiteName;
    char *currentTestName;
    Uint64 execKey;
    float runStartSeconds;
    float suiteStartSeconds;
    float testStartSeconds;
    float runEndSeconds;
    float suiteEndSeconds;
    float testEndSeconds;
    float runtime;
    int suiteFilter = 0;
    char *suiteFilterName = NULL;
    int testFilter = 0;
    char *testFilterName = NULL;
	SDL_bool forceTestRun = SDL_FALSE;
    int testResult = 0;
    int runResult = 0;
    Uint32 totalTestFailedCount = 0;
    Uint32 totalTestPassedCount = 0;
    Uint32 totalTestSkippedCount = 0;
    Uint32 testFailedCount = 0;
    Uint32 testPassedCount = 0;
    Uint32 testSkippedCount = 0;
    Uint32 countSum = 0;
    char *logFormat = (char *)SDLTest_LogSummaryFormat;
    SDLTest_TestCaseReference **failedTests;

    /* Sanitize test iterations */
    if (testIterations < 1) {
        testIterations = 1;
    }

    /* Generate run see if we don't have one already */
    if (userRunSeed == NULL || userRunSeed[0] == '\0') {
        runSeed = SDLTest_GenerateRunSeed(16);
        if (runSeed == NULL) {
            SDLTest_LogError("Generating a random seed failed");
            return 2;
        }
    } else {
        runSeed = userRunSeed;
    }


    /* Reset per-run counters */
    totalTestFailedCount = 0;
    totalTestPassedCount = 0;
    totalTestSkippedCount = 0;

    /* Take time - run start */
    runStartSeconds = GetClock();

    /* Log run with fuzzer parameters */
    SDLTest_Log("::::: Test Run /w seed '%s' started\n", runSeed);

	/* Count the total number of tests */
    suiteCounter = 0;
    while (testSuites[suiteCounter]) {
        testSuite=(SDLTest_TestSuiteReference *)testSuites[suiteCounter];
        suiteCounter++;
        testCounter = 0;
        while (testSuite->testCases[testCounter])
        {
            testCounter++;
			totalNumberOfTests++;
		}
	}

	/* Pre-allocate an array for tracking failed tests (potentially all test cases) */
	failedTests = (SDLTest_TestCaseReference **)SDL_malloc(totalNumberOfTests * sizeof(SDLTest_TestCaseReference *));
	if (failedTests == NULL) {	
	   SDLTest_LogError("Unable to allocate cache for failed tests");
           SDL_Error(SDL_ENOMEM);	   
           return -1;
	}

    /* Initialize filtering */
    if (filter != NULL && filter[0] != '\0') {
        /* Loop over all suites to check if we have a filter match */
        suiteCounter = 0;
        while (testSuites[suiteCounter] && suiteFilter == 0) {
            testSuite=(SDLTest_TestSuiteReference *)testSuites[suiteCounter];
            suiteCounter++;
            if (testSuite->name != NULL && SDL_strcmp(filter, testSuite->name) == 0) {
                /* Matched a suite name */
                suiteFilter = 1;
                suiteFilterName = testSuite->name;
                SDLTest_Log("Filtering: running only suite '%s'", suiteFilterName);
                break;
            }

            /* Within each suite, loop over all test cases to check if we have a filter match */
            testCounter = 0;
            while (testSuite->testCases[testCounter] && testFilter == 0)
            {
                testCase=(SDLTest_TestCaseReference *)testSuite->testCases[testCounter];
                testCounter++;
                if (testCase->name != NULL && SDL_strcmp(filter, testCase->name) == 0) {
                    /* Matched a test name */
                    suiteFilter = 1;
                    suiteFilterName = testSuite->name;
                    testFilter = 1;
                    testFilterName = testCase->name;
                    SDLTest_Log("Filtering: running only test '%s' in suite '%s'", testFilterName, suiteFilterName);
                    break;
                }
            }
        }

        if (suiteFilter == 0 && testFilter == 0) {
            SDLTest_LogError("Filter '%s' did not match any test suite/case.", filter);
            SDLTest_Log("Exit code: 2");
            SDL_free(failedTests);
            return 2;
        }
    }

    /* Loop over all suites */
    suiteCounter = 0;
    while(testSuites[suiteCounter]) {
        testSuite=(SDLTest_TestSuiteReference *)testSuites[suiteCounter];
        currentSuiteName = (char *)((testSuite->name) ? testSuite->name : SDLTest_InvalidNameFormat);
        suiteCounter++;

        /* Filter suite if flag set and we have a name */
        if (suiteFilter == 1 && suiteFilterName != NULL && testSuite->name != NULL &&
            SDL_strcmp(suiteFilterName, testSuite->name) != 0) {
                /* Skip suite */
                SDLTest_Log("===== Test Suite %i: '%s' skipped\n",
                    suiteCounter,
                    currentSuiteName);
        } else {

            /* Reset per-suite counters */
            testFailedCount = 0;
            testPassedCount = 0;
            testSkippedCount = 0;

            /* Take time - suite start */
            suiteStartSeconds = GetClock();

            /* Log suite started */
            SDLTest_Log("===== Test Suite %i: '%s' started\n",
                suiteCounter,
                currentSuiteName);

            /* Loop over all test cases */
            testCounter = 0;
            while(testSuite->testCases[testCounter])
            {
                testCase=(SDLTest_TestCaseReference *)testSuite->testCases[testCounter];
                currentTestName = (char *)((testCase->name) ? testCase->name : SDLTest_InvalidNameFormat);
                testCounter++;

                /* Filter tests if flag set and we have a name */
                if (testFilter == 1 && testFilterName != NULL && testCase->name != NULL &&
                    SDL_strcmp(testFilterName, testCase->name) != 0) {
                        /* Skip test */
                        SDLTest_Log("===== Test Case %i.%i: '%s' skipped\n",
                            suiteCounter,
                            testCounter,
                            currentTestName);
                } else {
                    /* Override 'disabled' flag if we specified a test filter (i.e. force run for debugging) */
                    if (testFilter == 1 && !testCase->enabled) {
                        SDLTest_Log("Force run of disabled test since test filter was set");
						forceTestRun = SDL_TRUE;
                    }

                    /* Take time - test start */
                    testStartSeconds = GetClock();

                    /* Log test started */
                    SDLTest_Log("----- Test Case %i.%i: '%s' started",
                        suiteCounter,
                        testCounter,
                        currentTestName);
                    if (testCase->description != NULL && testCase->description[0] != '\0') {
                        SDLTest_Log("Test Description: '%s'",
                            (testCase->description) ? testCase->description : SDLTest_InvalidNameFormat);
                    }

                    /* Loop over all iterations */
                    iterationCounter = 0;
                    while(iterationCounter < testIterations)
                    {
                        iterationCounter++;

                        if (userExecKey != 0) {
                            execKey = userExecKey;
                        } else {
                            execKey = SDLTest_GenerateExecKey((char *)runSeed, testSuite->name, testCase->name, iterationCounter);
                        }

                        SDLTest_Log("Test Iteration %i: execKey %" SDL_PRIu64, iterationCounter, execKey);
						testResult = SDLTest_RunTest(testSuite, testCase, execKey, forceTestRun);

                        if (testResult == TEST_RESULT_PASSED) {
                            testPassedCount++;
                            totalTestPassedCount++;
                        } else if (testResult == TEST_RESULT_SKIPPED) {
                            testSkippedCount++;
                            totalTestSkippedCount++;
                        } else {
                            testFailedCount++;
                            totalTestFailedCount++;
                        }
                    }

                    /* Take time - test end */
                    testEndSeconds = GetClock();
                    runtime = testEndSeconds - testStartSeconds;
                    if (runtime < 0.0f) runtime = 0.0f;

                    if (testIterations > 1) {
                        /* Log test runtime */
                        SDLTest_Log("Runtime of %i iterations: %.1f sec", testIterations, runtime);
                        SDLTest_Log("Average Test runtime: %.5f sec", runtime / (float)testIterations);
                    } else {
                        /* Log test runtime */
                        SDLTest_Log("Total Test runtime: %.1f sec", runtime);
                    }

                    /* Log final test result */
                    switch (testResult) {
                    case TEST_RESULT_PASSED:
                        SDLTest_Log((char *)SDLTest_FinalResultFormat, "Test", currentTestName, "Passed");
                        break;
                    case TEST_RESULT_FAILED:
                        SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Test", currentTestName, "Failed");
                        break;
                    case TEST_RESULT_NO_ASSERT:
                        SDLTest_LogError((char *)SDLTest_FinalResultFormat,"Test", currentTestName, "No Asserts");
                        break;
                    }

                    /* Collect failed test case references for repro-step display */
                    if (testResult == TEST_RESULT_FAILED) {
                        failedTests[failedNumberOfTests] = testCase;
                        failedNumberOfTests++;
                    }
                }
            }

            /* Take time - suite end */
            suiteEndSeconds = GetClock();
            runtime = suiteEndSeconds - suiteStartSeconds;
            if (runtime < 0.0f) runtime = 0.0f;

            /* Log suite runtime */
            SDLTest_Log("Total Suite runtime: %.1f sec", runtime);

            /* Log summary and final Suite result */
            countSum = testPassedCount + testFailedCount + testSkippedCount;
            if (testFailedCount == 0)
            {
                SDLTest_Log(logFormat, "Suite", countSum, testPassedCount, testFailedCount, testSkippedCount);
                SDLTest_Log((char *)SDLTest_FinalResultFormat, "Suite", currentSuiteName, "Passed");
            }
            else
            {
                SDLTest_LogError(logFormat, "Suite", countSum, testPassedCount, testFailedCount, testSkippedCount);
                SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Suite", currentSuiteName, "Failed");
            }

        }
    }

    /* Take time - run end */
    runEndSeconds = GetClock();
    runtime = runEndSeconds - runStartSeconds;
    if (runtime < 0.0f) runtime = 0.0f;

    /* Log total runtime */
    SDLTest_Log("Total Run runtime: %.1f sec", runtime);

    /* Log summary and final run result */
    countSum = totalTestPassedCount + totalTestFailedCount + totalTestSkippedCount;
    if (totalTestFailedCount == 0)
    {
        runResult = 0;
        SDLTest_Log(logFormat, "Run", countSum, totalTestPassedCount, totalTestFailedCount, totalTestSkippedCount);
        SDLTest_Log((char *)SDLTest_FinalResultFormat, "Run /w seed", runSeed, "Passed");
    }
    else
    {
        runResult = 1;
        SDLTest_LogError(logFormat, "Run", countSum, totalTestPassedCount, totalTestFailedCount, totalTestSkippedCount);
        SDLTest_LogError((char *)SDLTest_FinalResultFormat, "Run /w seed", runSeed, "Failed");
    }

    /* Print repro steps for failed tests */
    if (failedNumberOfTests > 0) {
        SDLTest_Log("Harness input to repro failures:");
        for (testCounter = 0; testCounter < failedNumberOfTests; testCounter++) {
          SDLTest_Log(" --seed %s --filter %s", runSeed, failedTests[testCounter]->name);
        }
    }
    SDL_free(failedTests);

    SDLTest_Log("Exit code: %d", runResult);
    return runResult;
}
示例#16
0
static VOID VManUpdateRects(SDL_PrivateVideoData *pPVData,
                             SDL_Rect *pSDLRectWin, // window rectangle on screen
                             SDL_Rect *pSDLRectFrame, // surface rectangle on window
                             int cRects, // number of record to update
                             SDL_Rect *pRects) // records to update
{
  BMAPINFO		bmiSrc;
  BMAPINFO		bmiDst;
  HWREQIN		sHWReqIn;
  BITBLTINFO		sBitbltInfo = { 0 };
  PRECTL		prectlScreenUpdate;
  RECTL			rclItem;
  RECTL			rclSrcBounds;
  RECTL			rclDstBounds;
  PPOINTL		pptlSrcOrg;
  PBLTRECT		pbrDst;
  ULONG			ulIdx;
  PVIDEOMODE		pVideoMode;

  bmiSrc.ulLength = sizeof(BMAPINFO);
  bmiSrc.ulType = BMAP_MEMORY;
  bmiSrc.ulWidth = pPVData->pSDLSurface->w;
  bmiSrc.ulHeight = pPVData->pSDLSurface->h;
  bmiSrc.ulBpp = pPVData->pSDLSurface->format->BitsPerPixel;
  bmiSrc.ulBytesPerLine = pPVData->pSDLSurface->pitch;
  bmiSrc.pBits = (PBYTE)pPVData->pSDLSurface->pixels;

  pVideoMode = pPVData->fFullscreen ?
                 pPVData->pFSVideoMode : pPVData->pDesktopVideoMode;
  bmiDst.ulLength = sizeof(BMAPINFO);
  bmiDst.ulType = BMAP_VRAM;
  bmiDst.pBits = (PBYTE)ulVRAMAddress;
  bmiDst.ulWidth = pVideoMode->sSDLRect.w;
  bmiDst.ulHeight = pVideoMode->sSDLRect.h;
  bmiDst.ulBpp = pVideoMode->uiBPP;
  bmiDst.ulBytesPerLine = pVideoMode->uiScanLineSize;

  // Fill lists: source coordinates (pptlSrcOrg), detination screen rectangles
  // (pbrDst), screen update rectangles (prectlScreenUpdate), calc source bound
  // (rclSrcBounds).

  pptlSrcOrg = SDL_malloc( cRects * sizeof(POINTL) );
  if ( pptlSrcOrg == NULL )
  {
    SDL_NotEnoughMemory();
    return;
  }
  pbrDst = SDL_malloc( cRects * sizeof(BLTRECT) );
  if ( pptlSrcOrg == NULL )
  {
    SDL_NotEnoughMemory();
    SDL_free( pptlSrcOrg );
    return;
  }
  prectlScreenUpdate = SDL_malloc( cRects * sizeof(RECTL) );
  if ( pptlSrcOrg == NULL )
  {
    SDL_NotEnoughMemory();
    SDL_free( pbrDst );
    SDL_free( pptlSrcOrg );
    return;
  }
  WinSetRectEmpty( pPVData->hab, &rclSrcBounds );

  for( ulIdx = 0; ulIdx < cRects; ulIdx++, pRects++ )
  {
    pptlSrcOrg[ulIdx].x = pRects->x;
    pptlSrcOrg[ulIdx].y = pRects->y;
    pbrDst[ulIdx].ulXOrg = pRects->x + pSDLRectWin->x + pSDLRectFrame->x;
    pbrDst[ulIdx].ulYOrg = pRects->y + pSDLRectWin->y + pSDLRectFrame->y;
    pbrDst[ulIdx].ulXExt = pRects->w;
    pbrDst[ulIdx].ulYExt = pRects->h;

    rclItem.xLeft = pRects->x;
    rclItem.xRight = pRects->x + pRects->w - 1;
    rclItem.yTop = bmiSrc.ulHeight - pRects->y;
    rclItem.yBottom = rclItem.yTop - pRects->h + 1;
    WinUnionRect( pPVData->hab, &rclSrcBounds, &rclSrcBounds, &rclItem );

    WinOffsetRect( pPVData->hab, &rclItem, pSDLRectWin->x + pSDLRectFrame->x,
                   bmiDst.ulHeight - (pSDLRectWin->y + pSDLRectFrame->y) );
    WinCopyRect( pPVData->hab, &prectlScreenUpdate[ulIdx], &rclItem );
  }

  if ( WinIsRectEmpty( pPVData->hab, &rclSrcBounds ) )
    return;

  // Detination bounding rectangle
  WinCopyRect( pPVData->hab, &rclDstBounds, &rclSrcBounds );
  WinOffsetRect( pPVData->hab, &rclDstBounds, pSDLRectWin->x + pSDLRectFrame->x,
                 bmiDst.ulHeight - (pSDLRectWin->y + pSDLRectFrame->y) );

  // Request HW
  sHWReqIn.ulLength = sizeof(HWREQIN);
  sHWReqIn.ulFlags = REQUEST_HW;
  sHWReqIn.cScrChangeRects = cRects;
  sHWReqIn.arectlScreen = prectlScreenUpdate;
  if ( pfnVMIEntry( 0, VMI_CMD_REQUESTHW, &sHWReqIn, NULL ) != RC_SUCCESS )
  {
    debug( "pfnVMIEntry(,VMI_CMD_REQUESTHW,,) failed" );
  }
  else
  {
    sBitbltInfo.ulLength = sizeof(BITBLTINFO);
    sBitbltInfo.ulBltFlags = BF_DEFAULT_STATE | BF_ROP_INCL_SRC | BF_PAT_HOLLOW;
    sBitbltInfo.cBlits = cRects;
    sBitbltInfo.ulROP = ROP_SRCCOPY;
    sBitbltInfo.pSrcBmapInfo = &bmiSrc;
    sBitbltInfo.pDstBmapInfo = &bmiDst;
    sBitbltInfo.prclSrcBounds = &rclSrcBounds;
    sBitbltInfo.prclDstBounds = &rclDstBounds;
    sBitbltInfo.aptlSrcOrg = pptlSrcOrg;
    sBitbltInfo.abrDst = pbrDst;

    if ( pfnVMIEntry( 0, VMI_CMD_BITBLT, &sBitbltInfo, NULL ) != RC_SUCCESS )
    {
      debug( "pfnVMIEntry(,VMI_CMD_BITBLT,,) failed" );
    }
    else
    {
      // Release HW
      sHWReqIn.ulFlags = 0;
      if ( pfnVMIEntry( 0, VMI_CMD_REQUESTHW, &sHWReqIn, NULL ) != RC_SUCCESS )
        debug( "pfnVMIEntry(,VMI_CMD_REQUESTHW,,) failed" );
    }
  }

  SDL_free( prectlScreenUpdate );
  SDL_free( pptlSrcOrg );
  SDL_free( pbrDst );
}
示例#17
0
static SDL_Surface *PZM_SetVideoMode(_THIS, SDL_Surface *current,
				     int width, int height, int bpp, Uint32 flags)
{
	Uint32 rmask = 0, gmask = 0, bmask = 0;

	width = ( width > SCREEN_WIDTH ) ? SCREEN_WIDTH : width;
	height = ( height > SCREEN_HEIGHT ) ? SCREEN_HEIGHT : height;
	bpp = ( bpp < 16 ) ? 8 : 16;

	PZM_DPRINT("Initializing display (%dx%dx%d)", width, height, bpp);

	this->info.current_w = width;
	this->info.current_h = height;

	if ( width < SCREEN_WIDTH || height < SCREEN_HEIGHT ) {
		int offset_x = (SCREEN_WIDTH - width) / 2;
		int offset_y = (SCREEN_HEIGHT - height) / 2;
		/*this->hidden->offset = this->hidden->cx
				     ? (int)PZM_PIXEL_ADDR(0, offset_x, offset_y, 2 * SCREEN_WIDTH, 2)
				     : (int)PZM_PIXEL_ADDR(0, offset_x / 2, offset_y, SCREEN_WIDTH / 2, 1);
		this->hidden->offset_x = offset_x;
		memset(VRAM, 0, SCREEN_BYTES_SIZE);
	} else
		this->hidden->offset = this->hidden->offset_x = 0;*/
		rmask = PZM_RMASK16;
		gmask = PZM_GMASK16;
		bmask = PZM_BMASK16;
	}

	if ( this->hidden->buffer ) {
		SDL_free( this->hidden->buffer );
	}

	this->hidden->buffer = SDL_malloc((bpp / 8) * width * height);
	if ( ! this->hidden->buffer ) {
		SDL_SetError("Couldn't allocate buffer for requested mode");
		return(NULL);
	}

	memset(this->hidden->buffer, 0, (bpp / 8) * width * height);

	/* Allocate the new pixel format for the screen */
	if ( ! SDL_ReallocFormat(current, bpp, rmask, gmask, bmask, 0) ) {
		SDL_free(this->hidden->buffer);
		this->hidden->buffer = NULL;
		SDL_SetError("Couldn't allocate new pixel format for requested mode");
		return(NULL);
	}

	/* Set up the new mode framebuffer */
	current->flags = flags;
	this->hidden->w = current->w = width;
	this->hidden->h = current->h = height;
	current->pitch = (bpp / 8) * current->w;
	current->pixels = this->hidden->buffer;

	PZM_DPRINT("Done (0x%p)", current);

	/* We're done */
	return(current);
}
示例#18
0
static int SDLCALL
windows_file_open(SDL_RWops * context, const char *filename, const char *mode)
{
    UINT old_error_mode;
    HANDLE h;
    DWORD r_right, w_right;
    DWORD must_exist, truncate;
    int a_mode;

    if (!context)
        return -1;              /* failed (invalid call) */

    context->hidden.windowsio.h = INVALID_HANDLE_VALUE;   /* mark this as unusable */
    context->hidden.windowsio.buffer.data = NULL;
    context->hidden.windowsio.buffer.size = 0;
    context->hidden.windowsio.buffer.left = 0;

    /* "r" = reading, file must exist */
    /* "w" = writing, truncate existing, file may not exist */
    /* "r+"= reading or writing, file must exist            */
    /* "a" = writing, append file may not exist             */
    /* "a+"= append + read, file may not exist              */
    /* "w+" = read, write, truncate. file may not exist    */

    must_exist = (SDL_strchr(mode, 'r') != NULL) ? OPEN_EXISTING : 0;
    truncate = (SDL_strchr(mode, 'w') != NULL) ? CREATE_ALWAYS : 0;
    r_right = (SDL_strchr(mode, '+') != NULL
               || must_exist) ? GENERIC_READ : 0;
    a_mode = (SDL_strchr(mode, 'a') != NULL) ? OPEN_ALWAYS : 0;
    w_right = (a_mode || SDL_strchr(mode, '+')
               || truncate) ? GENERIC_WRITE : 0;

    if (!r_right && !w_right)   /* inconsistent mode */
        return -1;              /* failed (invalid call) */

    context->hidden.windowsio.buffer.data =
        (char *) SDL_malloc(READAHEAD_BUFFER_SIZE);
    if (!context->hidden.windowsio.buffer.data) {
        return SDL_OutOfMemory();
    }
    /* Do not open a dialog box if failure */
    old_error_mode =
        SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);

    {
        LPTSTR tstr = WIN_UTF8ToString(filename);
        h = CreateFile(tstr, (w_right | r_right),
                       (w_right) ? 0 : FILE_SHARE_READ, NULL,
                       (must_exist | truncate | a_mode),
                       FILE_ATTRIBUTE_NORMAL, NULL);
        SDL_free(tstr);
    }

    /* restore old behavior */
    SetErrorMode(old_error_mode);

    if (h == INVALID_HANDLE_VALUE) {
        SDL_free(context->hidden.windowsio.buffer.data);
        context->hidden.windowsio.buffer.data = NULL;
        SDL_SetError("Couldn't open %s", filename);
        return -2;              /* failed (CreateFile) */
    }
    context->hidden.windowsio.h = h;
    context->hidden.windowsio.append = a_mode ? SDL_TRUE : SDL_FALSE;

    return 0;                   /* ok */
}
示例#19
0
WMcursor *GEM_CreateWMCursor(_THIS,
		Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
{
	WMcursor *cursor;
	MFORM *new_mform;
	int i;

#ifdef DEBUG_VIDEO_GEM
	Uint16 *data1, *mask1;

	printf("sdl:video:gem: create cursor\n");
#endif

	/* Check the size */
	if ( (w > MAXCURWIDTH) || (h > MAXCURHEIGHT) ) {
		SDL_SetError("Only cursors of dimension (%dx%d) are allowed",
							MAXCURWIDTH, MAXCURHEIGHT);
		return(NULL);
	}

	/* Allocate the cursor memory */
	cursor = (WMcursor *)SDL_malloc(sizeof(WMcursor));
	if ( cursor == NULL ) {
		SDL_OutOfMemory();
		return(NULL);
	}

	/* Allocate mform */
	new_mform = (MFORM *)SDL_malloc(sizeof(MFORM));		
	if (new_mform == NULL) {
		SDL_free(cursor);
		SDL_OutOfMemory();
		return(NULL);
	}

	cursor->mform_p = new_mform;

	new_mform->mf_xhot = hot_x;
	new_mform->mf_yhot = hot_y;
	new_mform->mf_nplanes = 1;
	new_mform->mf_fg = 0;
	new_mform->mf_bg = 1;

	for (i=0;i<MAXCURHEIGHT;i++) {
		new_mform->mf_mask[i]=0;
		new_mform->mf_data[i]=0;
#ifdef DEBUG_VIDEO_GEM
		data1 = (Uint16 *) &data[i<<1];
		mask1 = (Uint16 *) &mask[i<<1];
		printf("sdl:video:gem: source: line %d: data=0x%04x, mask=0x%04x\n",
			i, data1[i], mask1[i]);
#endif
	}

	if (w<=8) {
		for (i=0;i<h;i++) {
			new_mform->mf_mask[i]= mask[i]<<8;
			new_mform->mf_data[i]= data[i]<<8;
		}
	} else {
		for (i=0;i<h;i++) {
			new_mform->mf_mask[i]= (mask[i<<1]<<8) | mask[(i<<1)+1];
			new_mform->mf_data[i]= (data[i<<1]<<8) | data[(i<<1)+1];
		}
	}

#ifdef DEBUG_VIDEO_GEM
	for (i=0; i<h ;i++) {
		printf("sdl:video:gem: cursor: line %d: data=0x%04x, mask=0x%04x\n",
			i, new_mform->mf_data[i], new_mform->mf_mask[i]);
	}

	printf("sdl:video:gem: CreateWMCursor(): done\n");
#endif

	return cursor;
}
示例#20
0
int
SDL_setenv(const char *name, const char *value, int overwrite)
{
    int added;
    int len, i;
    char **new_env;
    char *new_variable;

    /* A little error checking */
    if (!name || !value) {
        return (-1);
    }

    /* See if it already exists */
    if (!overwrite && SDL_getenv(name)) {
        return 0;
    }

    /* Allocate memory for the variable */
    len = SDL_strlen(name) + SDL_strlen(value) + 2;
    new_variable = (char *) SDL_malloc(len);
    if (!new_variable) {
        return (-1);
    }

    SDL_snprintf(new_variable, len, "%s=%s", name, value);
    value = new_variable + SDL_strlen(name) + 1;
    name = new_variable;

    /* Actually put it into the environment */
    added = 0;
    i = 0;
    if (SDL_env) {
        /* Check to see if it's already there... */
        len = (value - name);
        for (; SDL_env[i]; ++i) {
            if (SDL_strncmp(SDL_env[i], name, len) == 0) {
                break;
            }
        }
        /* If we found it, just replace the entry */
        if (SDL_env[i]) {
            SDL_free(SDL_env[i]);
            SDL_env[i] = new_variable;
            added = 1;
        }
    }

    /* Didn't find it in the environment, expand and add */
    if (!added) {
        new_env = SDL_realloc(SDL_env, (i + 2) * sizeof(char *));
        if (new_env) {
            SDL_env = new_env;
            SDL_env[i++] = new_variable;
            SDL_env[i++] = (char *) 0;
            added = 1;
        } else {
            SDL_free(new_variable);
        }
    }
    return (added ? 0 : -1);
}
示例#21
0
static SDL_VideoDevice * NX_CreateDevice (int devindex)
{
    SDL_VideoDevice * device ;

    Dprintf ("enter NX_CreateDevice\n") ;

    // Initialize all variables that we clean on shutdown
    device = (SDL_VideoDevice *) SDL_malloc (sizeof (SDL_VideoDevice)) ;
    if (device) {
        SDL_memset (device, 0, (sizeof * device)) ;
        device -> hidden = (struct SDL_PrivateVideoData *)
                SDL_malloc ((sizeof * device -> hidden)) ;
        device -> gl_data = NULL ;
    }
    if ((device == NULL) || (device -> hidden == NULL)) {
        SDL_OutOfMemory () ;
        NX_DeleteDevice (device) ;
        return 0 ;
    }
    SDL_memset (device -> hidden, 0, (sizeof * device -> hidden)) ;

    // Set the function pointers
    device -> VideoInit = NX_VideoInit ;
    device -> ListModes = NX_ListModes ;
    device -> SetVideoMode = NX_SetVideoMode ;
    device -> ToggleFullScreen = NX_ToggleFullScreen ;
    device -> UpdateMouse = NX_UpdateMouse ;
    device -> CreateYUVOverlay = NULL ;
    device -> SetColors = NX_SetColors ;
    device -> UpdateRects = NULL ;
    device -> VideoQuit = NX_VideoQuit;
    device -> AllocHWSurface = NULL ;
    device -> CheckHWBlit = NULL ;
    device -> FillHWRect = NULL ;
    device -> SetHWColorKey = NULL ;
    device -> SetHWAlpha = NULL ;
    device -> LockHWSurface = NULL ;
    device -> UnlockHWSurface = NULL ;
    device -> FlipHWSurface = NULL ;
    device -> FreeHWSurface = NULL ;
    device -> SetGamma = NULL ;
    device -> GetGamma = NULL ;
    device -> SetGammaRamp = NX_SetGammaRamp ;
    device -> GetGammaRamp = NX_GetGammaRamp ;

#if SDL_VIDEO_OPENGL
    device -> GL_LoadLibrary = NULL ;
    device -> GL_GetProcAddress = NULL ;
    device -> GL_GetAttribute = NULL ;
    device -> GL_MakeCurrent = NULL ;
    device -> GL_SwapBuffers = NULL ;
#endif

    device -> SetIcon = NULL ;
    device -> SetCaption = NX_SetCaption;
    device -> IconifyWindow = NULL ;
    device -> GrabInput = NULL ;
    device -> GetWMInfo = NX_GetWMInfo ;
    device -> FreeWMCursor =  NX_FreeWMCursor ;
    device -> CreateWMCursor = NX_CreateWMCursor ;
    device -> ShowWMCursor = NX_ShowWMCursor ;
    device -> WarpWMCursor = NX_WarpWMCursor ;
    device -> CheckMouseMode = NULL ;
    device -> InitOSKeymap = NX_InitOSKeymap ;
    device -> PumpEvents = NX_PumpEvents ;

    device -> free = NX_DeleteDevice ;

    Dprintf ("leave NX_CreateDevice\n") ;
    return device ;
}
static int
DMA_OpenDevice(_THIS, const char *devname, int iscapture)
{
    const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT);
    int format;
    int stereo;
    int value;
    SDL_AudioFormat test_format;
    struct audio_buf_info info;

    /* We don't care what the devname is...we'll try to open anything. */
    /*  ...but default to first name in the list... */
    if (devname == NULL) {
        if (((iscapture) && (inputDeviceCount == 0)) ||
            ((!iscapture) && (outputDeviceCount == 0))) {
            SDL_SetError("No such audio device");
            return 0;
        }
        devname = ((iscapture) ? inputDevices[0] : outputDevices[0]);
    }

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        SDL_OutOfMemory();
        return 0;
    }
    SDL_memset(this->hidden, 0, (sizeof *this->hidden));

    /* Open the audio device */
    audio_fd = open(devname, flags, 0);
    if (audio_fd < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't open %s: %s", devname, strerror(errno));
        return 0;
    }
    dma_buf = NULL;
    ioctl(audio_fd, SNDCTL_DSP_RESET, 0);

    /* Get a list of supported hardware formats */
    if (ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't get audio format list");
        return 0;
    }

    /* Try for a closest match on audio format */
    format = 0;
    for (test_format = SDL_FirstAudioFormat(this->spec.format);
         !format && test_format;) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
#endif
        switch (test_format) {
        case AUDIO_U8:
            if (value & AFMT_U8) {
                format = AFMT_U8;
            }
            break;
        case AUDIO_S8:
            if (value & AFMT_S8) {
                format = AFMT_S8;
            }
            break;
        case AUDIO_S16LSB:
            if (value & AFMT_S16_LE) {
                format = AFMT_S16_LE;
            }
            break;
        case AUDIO_S16MSB:
            if (value & AFMT_S16_BE) {
                format = AFMT_S16_BE;
            }
            break;
        case AUDIO_U16LSB:
            if (value & AFMT_U16_LE) {
                format = AFMT_U16_LE;
            }
            break;
        case AUDIO_U16MSB:
            if (value & AFMT_U16_BE) {
                format = AFMT_U16_BE;
            }
            break;
        default:
            format = 0;
            break;
        }
        if (!format) {
            test_format = SDL_NextAudioFormat();
        }
    }
    if (format == 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't find any hardware audio formats");
        return 0;
    }
    this->spec.format = test_format;

    /* Set the audio format */
    value = format;
    if ((ioctl(audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) || (value != format)) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't set audio format");
        return 0;
    }

    /* Set mono or stereo audio (currently only two channels supported) */
    stereo = (this->spec.channels > 1);
    ioctl(audio_fd, SNDCTL_DSP_STEREO, &stereo);
    if (stereo) {
        this->spec.channels = 2;
    } else {
        this->spec.channels = 1;
    }

    /* Because some drivers don't allow setting the buffer size
       after setting the format, we must re-open the audio device
       once we know what format and channels are supported
     */
    if (DMA_ReopenAudio(this, devname, format, stereo) < 0) {
        DMA_CloseDevice(this);
        /* Error is set by DMA_ReopenAudio() */
        return 0;
    }

    /* Memory map the audio buffer */
    if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info) < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't get OSPACE parameters");
        return 0;
    }
    this->spec.size = info.fragsize;
    this->spec.samples = this->spec.size / ((this->spec.format & 0xFF) / 8);
    this->spec.samples /= this->spec.channels;
    num_buffers = info.fragstotal;
    dma_len = num_buffers * this->spec.size;
    dma_buf = (Uint8 *) mmap(NULL, dma_len, PROT_WRITE, MAP_SHARED,
                             audio_fd, 0);
    if (dma_buf == MAP_FAILED) {
        DMA_CloseDevice(this);
        SDL_SetError("DMA memory map failed");
        dma_buf = NULL;
        return 0;
    }
    SDL_memset(dma_buf, this->spec.silence, dma_len);

    /* Check to see if we need to use select() workaround */
    {
        char *workaround;
        workaround = SDL_getenv("SDL_DSP_NOSELECT");
        if (workaround) {
            frame_ticks =
                (float) (this->spec.samples * 1000) / this->spec.freq;
            next_frame = SDL_GetTicks() + frame_ticks;
        }
    }

    /* Trigger audio playback */
    value = 0;
    ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value);
    value = PCM_ENABLE_OUTPUT;
    if (ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &value) < 0) {
        DMA_CloseDevice(this);
        SDL_SetError("Couldn't trigger audio output");
        return 0;
    }

    /* Get the parent process id (we're the parent of the audio thread) */
    parent = getpid();

    /* We're ready to rock and roll. :-) */
    return 1;
}
示例#23
0
static int
DSOUND_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
{
    const DWORD numchunks = 8;
    HRESULT result;
    SDL_bool valid_format = SDL_FALSE;
    SDL_bool tried_format = SDL_FALSE;
    SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
    LPGUID guid = (LPGUID) handle;
	DWORD bufsize;
	
    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        return SDL_OutOfMemory();
    }
    SDL_zerop(this->hidden);

    /* Open the audio device */
    if (iscapture) {
        result = pDirectSoundCaptureCreate8(guid, &this->hidden->capture, NULL);
        if (result != DS_OK) {
            return SetDSerror("DirectSoundCaptureCreate8", result);
        }
    } else {
        result = pDirectSoundCreate8(guid, &this->hidden->sound, NULL);
        if (result != DS_OK) {
            return SetDSerror("DirectSoundCreate8", result);
        }
        result = IDirectSound_SetCooperativeLevel(this->hidden->sound,
                                                  GetDesktopWindow(),
                                                  DSSCL_NORMAL);
        if (result != DS_OK) {
            return SetDSerror("DirectSound SetCooperativeLevel", result);
        }
    }

    while ((!valid_format) && (test_format)) {
        switch (test_format) {
        case AUDIO_U8:
        case AUDIO_S16:
        case AUDIO_S32:
        case AUDIO_F32:
            tried_format = SDL_TRUE;

            this->spec.format = test_format;

            /* Update the fragment size as size in bytes */
            SDL_CalculateAudioSpec(&this->spec);

            bufsize = numchunks * this->spec.size;
            if ((bufsize < DSBSIZE_MIN) || (bufsize > DSBSIZE_MAX)) {
                SDL_SetError("Sound buffer size must be between %d and %d",
                             (DSBSIZE_MIN < numchunks) ? 1 : DSBSIZE_MIN / numchunks,
                             DSBSIZE_MAX / numchunks);
            } else {
                int rc;
				WAVEFORMATEX wfmt;
                SDL_zero(wfmt);
                if (SDL_AUDIO_ISFLOAT(this->spec.format)) {
                    wfmt.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
                } else {
                    wfmt.wFormatTag = WAVE_FORMAT_PCM;
                }

                wfmt.wBitsPerSample = SDL_AUDIO_BITSIZE(this->spec.format);
                wfmt.nChannels = this->spec.channels;
                wfmt.nSamplesPerSec = this->spec.freq;
                wfmt.nBlockAlign = wfmt.nChannels * (wfmt.wBitsPerSample / 8);
                wfmt.nAvgBytesPerSec = wfmt.nSamplesPerSec * wfmt.nBlockAlign;

                rc = iscapture ? CreateCaptureBuffer(this, bufsize, &wfmt) : CreateSecondary(this, bufsize, &wfmt);
                if (rc == 0) {
                    this->hidden->num_buffers = numchunks;
                    valid_format = SDL_TRUE;
                }
            }
            break;
        }
        test_format = SDL_NextAudioFormat();
    }

    if (!valid_format) {
        if (tried_format) {
            return -1;  /* CreateSecondary() should have called SDL_SetError(). */
        }
        return SDL_SetError("DirectSound: Unsupported audio format");
    }

    /* Playback buffers will auto-start playing in DSOUND_WaitDevice() */

    return 0;                   /* good to go. */
}
示例#24
0
static int
DSP_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
{
    const int flags = ((iscapture) ? OPEN_FLAGS_INPUT : OPEN_FLAGS_OUTPUT);
    int format;
    int value;
    int frag_spec;
    SDL_AudioFormat test_format;

    /* We don't care what the devname is...we'll try to open anything. */
    /*  ...but default to first name in the list... */
    if (devname == NULL) {
        devname = SDL_GetAudioDeviceName(0, iscapture);
        if (devname == NULL) {
            return SDL_SetError("No such audio device");
        }
    }

    /* Make sure fragment size stays a power of 2, or OSS fails. */
    /* I don't know which of these are actually legal values, though... */
    if (this->spec.channels > 8)
        this->spec.channels = 8;
    else if (this->spec.channels > 4)
        this->spec.channels = 4;
    else if (this->spec.channels > 2)
        this->spec.channels = 2;

    /* Initialize all variables that we clean on shutdown */
    this->hidden = (struct SDL_PrivateAudioData *)
        SDL_malloc((sizeof *this->hidden));
    if (this->hidden == NULL) {
        return SDL_OutOfMemory();
    }
    SDL_zerop(this->hidden);

    /* Open the audio device */
    this->hidden->audio_fd = open(devname, flags, 0);
    if (this->hidden->audio_fd < 0) {
        return SDL_SetError("Couldn't open %s: %s", devname, strerror(errno));
    }

    /* Make the file descriptor use blocking i/o with fcntl() */
    {
        long ctlflags;
        ctlflags = fcntl(this->hidden->audio_fd, F_GETFL);
        ctlflags &= ~O_NONBLOCK;
        if (fcntl(this->hidden->audio_fd, F_SETFL, ctlflags) < 0) {
            return SDL_SetError("Couldn't set audio blocking mode");
        }
    }

    /* Get a list of supported hardware formats */
    if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_GETFMTS, &value) < 0) {
        perror("SNDCTL_DSP_GETFMTS");
        return SDL_SetError("Couldn't get audio format list");
    }

    /* Try for a closest match on audio format */
    format = 0;
    for (test_format = SDL_FirstAudioFormat(this->spec.format);
         !format && test_format;) {
#ifdef DEBUG_AUDIO
        fprintf(stderr, "Trying format 0x%4.4x\n", test_format);
#endif
        switch (test_format) {
        case AUDIO_U8:
            if (value & AFMT_U8) {
                format = AFMT_U8;
            }
            break;
        case AUDIO_S16LSB:
            if (value & AFMT_S16_LE) {
                format = AFMT_S16_LE;
            }
            break;
        case AUDIO_S16MSB:
            if (value & AFMT_S16_BE) {
                format = AFMT_S16_BE;
            }
            break;
#if 0
/*
 * These formats are not used by any real life systems so they are not
 * needed here.
 */
        case AUDIO_S8:
            if (value & AFMT_S8) {
                format = AFMT_S8;
            }
            break;
        case AUDIO_U16LSB:
            if (value & AFMT_U16_LE) {
                format = AFMT_U16_LE;
            }
            break;
        case AUDIO_U16MSB:
            if (value & AFMT_U16_BE) {
                format = AFMT_U16_BE;
            }
            break;
#endif
        default:
            format = 0;
            break;
        }
        if (!format) {
            test_format = SDL_NextAudioFormat();
        }
    }
    if (format == 0) {
        return SDL_SetError("Couldn't find any hardware audio formats");
    }
    this->spec.format = test_format;

    /* Set the audio format */
    value = format;
    if ((ioctl(this->hidden->audio_fd, SNDCTL_DSP_SETFMT, &value) < 0) ||
        (value != format)) {
        perror("SNDCTL_DSP_SETFMT");
        return SDL_SetError("Couldn't set audio format");
    }

    /* Set the number of channels of output */
    value = this->spec.channels;
    if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_CHANNELS, &value) < 0) {
        perror("SNDCTL_DSP_CHANNELS");
        return SDL_SetError("Cannot set the number of channels");
    }
    this->spec.channels = value;

    /* Set the DSP frequency */
    value = this->spec.freq;
    if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_SPEED, &value) < 0) {
        perror("SNDCTL_DSP_SPEED");
        return SDL_SetError("Couldn't set audio frequency");
    }
    this->spec.freq = value;

    /* Calculate the final parameters for this audio specification */
    SDL_CalculateAudioSpec(&this->spec);

    /* Determine the power of two of the fragment size */
    for (frag_spec = 0; (0x01U << frag_spec) < this->spec.size; ++frag_spec);
    if ((0x01U << frag_spec) != this->spec.size) {
        return SDL_SetError("Fragment size must be a power of two");
    }
    frag_spec |= 0x00020000;    /* two fragments, for low latency */

    /* Set the audio buffering parameters */
#ifdef DEBUG_AUDIO
    fprintf(stderr, "Requesting %d fragments of size %d\n",
            (frag_spec >> 16), 1 << (frag_spec & 0xFFFF));
#endif
    if (ioctl(this->hidden->audio_fd, SNDCTL_DSP_SETFRAGMENT, &frag_spec) < 0) {
        perror("SNDCTL_DSP_SETFRAGMENT");
    }
#ifdef DEBUG_AUDIO
    {
        audio_buf_info info;
        ioctl(this->hidden->audio_fd, SNDCTL_DSP_GETOSPACE, &info);
        fprintf(stderr, "fragments = %d\n", info.fragments);
        fprintf(stderr, "fragstotal = %d\n", info.fragstotal);
        fprintf(stderr, "fragsize = %d\n", info.fragsize);
        fprintf(stderr, "bytes = %d\n", info.bytes);
    }
#endif

    /* Allocate mixing buffer */
    if (!iscapture) {
        this->hidden->mixlen = this->spec.size;
        this->hidden->mixbuf = (Uint8 *) SDL_malloc(this->hidden->mixlen);
        if (this->hidden->mixbuf == NULL) {
            return SDL_OutOfMemory();
        }
        SDL_memset(this->hidden->mixbuf, this->spec.silence, this->spec.size);
    }

    /* We're ready to rock and roll. :-) */
    return 0;
}
示例#25
0
SDL_AudioSpec *Mix_LoadMP3_RW(SDL_RWops *src, int freesrc, SDL_AudioSpec *spec, Uint8 **audio_buf, Uint32 *audio_len)
{
	/* note: spec is initialized to mixer spec */

#if defined(MP3_MUSIC)
	SMPEG* mp3 = 0;
	SMPEG_Info info;
#elif defined(MP3_MAD_MUSIC)
	mad_data *mp3_mad;
#endif
	long samplesize;
	int read_len;
	const Uint32 chunk_len = 4096;
	int err = 0;

	if ((!src) || (!spec) || (!audio_buf) || (!audio_len))
	{
		return NULL;
	}

	if (!err)
	{
		*audio_len = 0;
		*audio_buf = (Uint8*) SDL_malloc(chunk_len);
		err = (*audio_buf == NULL);
	}

	if (!err)
	{
		err = ((Mix_Init(MIX_INIT_MP3) & MIX_INIT_MP3) == 0);
	}

	if (!err)
	{
#if defined(MP3_MUSIC)
		mp3 = smpeg.SMPEG_new_rwops(src, &info, freesrc, 0);
		err = (mp3 == NULL);
#elif defined(MP3_MAD_MUSIC)
        mp3_mad = mad_openFileRW(src, spec, freesrc);
		err = (mp3_mad == NULL);
#endif
	}

#if defined(MP3_MUSIC)
	if (!err)
	{
		err = !info.has_audio;
	}
#endif

	if (!err)
	{
#if defined(MP3_MUSIC)

		smpeg.SMPEG_actualSpec(mp3, spec);

		smpeg.SMPEG_enableaudio(mp3, 1);
		smpeg.SMPEG_enablevideo(mp3, 0);

		smpeg.SMPEG_play(mp3);

		/* read once for audio length */
		while ((read_len = smpeg.SMPEG_playAudio(mp3, *audio_buf, chunk_len)) > 0)
		{
			*audio_len += read_len;
		}

		smpeg.SMPEG_stop(mp3);

#elif defined(MP3_MAD_MUSIC)

        mad_start(mp3_mad);

		/* read once for audio length */
		while ((read_len = mad_getSamples(mp3_mad, *audio_buf, chunk_len)) > 0)
		{
			*audio_len += read_len;
		}

		mad_stop(mp3_mad);

#endif

		err = (read_len < 0);
	}

	if (!err)
	{
		/* reallocate, if needed */
		if ((*audio_len > 0) && (*audio_len != chunk_len))
		{
			*audio_buf = (Uint8*) SDL_realloc(*audio_buf, *audio_len);
			err = (*audio_buf == NULL);
		}
	}

	if (!err)
	{
		/* read again for audio buffer, if needed */
		if (*audio_len > chunk_len)
		{
#if defined(MP3_MUSIC)
			smpeg.SMPEG_rewind(mp3);
			smpeg.SMPEG_play(mp3);
			err = (*audio_len != smpeg.SMPEG_playAudio(mp3, *audio_buf, *audio_len));
			smpeg.SMPEG_stop(mp3);
#elif defined(MP3_MAD_MUSIC)
			mad_seek(mp3_mad, 0);
			mad_start(mp3_mad);
			err = (*audio_len != mad_getSamples(mp3_mad, *audio_buf, *audio_len));
			mad_stop(mp3_mad);
#endif
		}
	}

	if (!err)
	{
		/* Don't return a buffer that isn't a multiple of samplesize */
		samplesize = ((spec->format & 0xFF)/8)*spec->channels;
		*audio_len &= ~(samplesize-1);
	}

#if defined(MP3_MUSIC)
	if (mp3)
	{
		smpeg.SMPEG_delete(mp3); mp3 = NULL;
		/* Deleting the MP3 closed the source if desired */
		freesrc = SDL_FALSE;
	}
#elif defined(MP3_MAD_MUSIC)
	if (mp3_mad)
	{
		mad_closeFile(mp3_mad); mp3_mad = NULL;
		/* Deleting the MP3 closed the source if desired */
		freesrc = SDL_FALSE;
	}
#endif

	if (freesrc)
	{
		SDL_RWclose(src); src = NULL;
	}

	/* handle error */
	if (err)
	{
		if (*audio_buf != NULL)
		{
			SDL_free(*audio_buf); *audio_buf = NULL;
		}
		*audio_len = 0;
		spec = NULL;
	}

	return spec;
}
static int ph_VideoInit(_THIS, SDL_PixelFormat* vformat)
{
    PgHWCaps_t hwcaps;
    int i;

    window=NULL;
    desktoppal=SDLPH_PAL_NONE;

#if SDL_VIDEO_OPENGL
    oglctx=NULL;
    oglbuffers=NULL;
    oglflags=0;
    oglbpp=0;
#endif
    
    old_video_mode=-1;
    old_refresh_rate=-1;
	
    if (NULL == (phevent = SDL_malloc(EVENT_SIZE)))
    {
        SDL_OutOfMemory();
        return -1;
    }
    SDL_memset(phevent, 0x00, EVENT_SIZE);

    window = ph_CreateWindow(this);
    if (window == NULL)
    {
        SDL_SetError("ph_VideoInit(): Couldn't create video window !\n");
        return -1;
    }

    /* Create the blank cursor */
    SDL_BlankCursor = this->CreateWMCursor(this, blank_cdata, blank_cmask,
                                          (int)BLANK_CWIDTH, (int)BLANK_CHEIGHT,
                                          (int)BLANK_CHOTX, (int)BLANK_CHOTY);

    if (SDL_BlankCursor == NULL)
    {
        return -1;
    }

    if (PgGetGraphicsHWCaps(&hwcaps) < 0)
    {
        SDL_SetError("ph_VideoInit(): GetGraphicsHWCaps function failed !\n");
        this->FreeWMCursor(this, SDL_BlankCursor);
        return -1;
    }

    if (PgGetVideoModeInfo(hwcaps.current_video_mode, &desktop_mode) < 0)
    {
        SDL_SetError("ph_VideoInit(): PgGetVideoModeInfo function failed !\n");
        this->FreeWMCursor(this, SDL_BlankCursor);
        return -1;
    }

   /* Determine the current screen size */
   this->info.current_w = desktop_mode.width;
   this->info.current_h = desktop_mode.height;

    /* We need to return BytesPerPixel as it in used by CreateRGBsurface */
    vformat->BitsPerPixel = desktop_mode.bits_per_pixel;
    vformat->BytesPerPixel = desktop_mode.bytes_per_scanline/desktop_mode.width;
    desktopbpp = desktop_mode.bits_per_pixel;
    
    /* save current palette */
    if (desktopbpp==8)
    {
        PgGetPalette(savedpal);
        PgGetPalette(syspalph);
    }
    else
    {
        for(i=0; i<_Pg_MAX_PALETTE; i++)
        {
            savedpal[i]=PgRGB(0, 0, 0);
            syspalph[i]=PgRGB(0, 0, 0);
        }
    }
         
    currently_fullscreen = 0;
    currently_hided = 0;
    currently_maximized = 0;
    current_overlay = NULL;

    OCImage.direct_context = NULL;
    OCImage.offscreen_context = NULL;
    OCImage.offscreen_backcontext = NULL;
    OCImage.oldDC = NULL;
    OCImage.CurrentFrameData = NULL;
    OCImage.FrameData0 = NULL;
    OCImage.FrameData1 = NULL;
    videomode_emulatemode = 0;
    
    this->info.wm_available = 1;

    ph_UpdateHWInfo(this);
    
    return 0;
}
示例#27
0
/*
 * Open a joystick for use - the index passed as an argument refers to
 * the N'th joystick on the system.  This index is the value which will
 * identify this joystick in future joystick events.
 *
 * This function returns a joystick identifier, or NULL if an error occurred.
 */
SDL_Joystick *
SDL_JoystickOpen(int device_index)
{
    SDL_Joystick *joystick;
    SDL_Joystick *joysticklist;
    const char *joystickname = NULL;

    if ((device_index < 0) || (device_index >= SDL_NumJoysticks())) {
        SDL_SetError("There are %d joysticks available", SDL_NumJoysticks());
        return (NULL);
    }

    joysticklist = SDL_joysticks;
    /* If the joystick is already open, return it
    * it is important that we have a single joystick * for each instance id
    */
    while (joysticklist) {
        if (SDL_SYS_GetInstanceIdOfDeviceIndex(device_index) == joysticklist->instance_id) {
                joystick = joysticklist;
                ++joystick->ref_count;
                return (joystick);
        }
        joysticklist = joysticklist->next;
    }

    /* Create and initialize the joystick */
    joystick = (SDL_Joystick *) SDL_malloc((sizeof *joystick));
    if (joystick == NULL) {
        SDL_OutOfMemory();
        return NULL;
    }

    SDL_memset(joystick, 0, (sizeof *joystick));
    if (SDL_SYS_JoystickOpen(joystick, device_index) < 0) {
        SDL_free(joystick);
        return NULL;
    }

    joystickname = SDL_SYS_JoystickNameForDeviceIndex(device_index);
    if (joystickname)
        joystick->name = SDL_strdup(joystickname);
    else
        joystick->name = NULL;

    if (joystick->naxes > 0) {
        joystick->axes = (Sint16 *) SDL_malloc
            (joystick->naxes * sizeof(Sint16));
    }
    if (joystick->nhats > 0) {
        joystick->hats = (Uint8 *) SDL_malloc
            (joystick->nhats * sizeof(Uint8));
    }
    if (joystick->nballs > 0) {
        joystick->balls = (struct balldelta *) SDL_malloc
            (joystick->nballs * sizeof(*joystick->balls));
    }
    if (joystick->nbuttons > 0) {
        joystick->buttons = (Uint8 *) SDL_malloc
            (joystick->nbuttons * sizeof(Uint8));
    }
    if (((joystick->naxes > 0) && !joystick->axes)
        || ((joystick->nhats > 0) && !joystick->hats)
        || ((joystick->nballs > 0) && !joystick->balls)
        || ((joystick->nbuttons > 0) && !joystick->buttons)) {
        SDL_OutOfMemory();
        SDL_JoystickClose(joystick);
        return NULL;
    }
    if (joystick->axes) {
        SDL_memset(joystick->axes, 0, joystick->naxes * sizeof(Sint16));
    }
    if (joystick->hats) {
        SDL_memset(joystick->hats, 0, joystick->nhats * sizeof(Uint8));
    }
    if (joystick->balls) {
        SDL_memset(joystick->balls, 0,
            joystick->nballs * sizeof(*joystick->balls));
    }
    if (joystick->buttons) {
        SDL_memset(joystick->buttons, 0, joystick->nbuttons * sizeof(Uint8));
    }
    joystick->epowerlevel = SDL_JOYSTICK_POWER_UNKNOWN;

    /* Add joystick to list */
    ++joystick->ref_count;
    /* Link the joystick in the list */
    joystick->next = SDL_joysticks;
    SDL_joysticks = joystick;

    SDL_SYS_JoystickUpdate(joystick);

    return (joystick);
}
static SDL_VideoDevice* ph_CreateDevice(int devindex)
{
    SDL_VideoDevice* device;

    /* Initialize all variables that we clean on shutdown */
    device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
    if (device)
    {
        SDL_memset(device, 0, (sizeof *device));
        device->hidden = (struct SDL_PrivateVideoData*)SDL_malloc((sizeof *device->hidden));
        device->gl_data = NULL;
    }
    if ((device == NULL) || (device->hidden == NULL))
    {
        SDL_OutOfMemory();
        ph_DeleteDevice(device);
        return NULL;
    }
    SDL_memset(device->hidden, 0, (sizeof *device->hidden));

    /* Set the driver flags */
    device->handles_any_size = 1;

    /* Set the function pointers */
    device->CreateYUVOverlay = ph_CreateYUVOverlay;
    device->VideoInit = ph_VideoInit;
    device->ListModes = ph_ListModes;
    device->SetVideoMode = ph_SetVideoMode;
    device->ToggleFullScreen = ph_ToggleFullScreen;
    device->UpdateMouse = ph_UpdateMouse;
    device->SetColors = ph_SetColors;
    device->UpdateRects = NULL;                        /* set up in ph_SetupUpdateFunction */
    device->VideoQuit = ph_VideoQuit;
    device->AllocHWSurface = ph_AllocHWSurface;
    device->CheckHWBlit = ph_CheckHWBlit;
    device->FillHWRect = ph_FillHWRect;
    device->SetHWColorKey = ph_SetHWColorKey;
    device->SetHWAlpha = ph_SetHWAlpha;
    device->LockHWSurface = ph_LockHWSurface;
    device->UnlockHWSurface = ph_UnlockHWSurface;
    device->FlipHWSurface = ph_FlipHWSurface;
    device->FreeHWSurface = ph_FreeHWSurface;
    device->SetCaption = ph_SetCaption;
    device->SetIcon = NULL;
    device->IconifyWindow = ph_IconifyWindow;
    device->GrabInput = ph_GrabInput;
    device->GetWMInfo = ph_GetWMInfo;
    device->FreeWMCursor = ph_FreeWMCursor;
    device->CreateWMCursor = ph_CreateWMCursor;
    device->ShowWMCursor = ph_ShowWMCursor;
    device->WarpWMCursor = ph_WarpWMCursor;
    device->MoveWMCursor = NULL;
    device->CheckMouseMode = ph_CheckMouseMode;
    device->InitOSKeymap = ph_InitOSKeymap;
    device->PumpEvents = ph_PumpEvents;

    /* OpenGL support. */
#if SDL_VIDEO_OPENGL
    device->GL_MakeCurrent = ph_GL_MakeCurrent;
    device->GL_SwapBuffers = ph_GL_SwapBuffers;
    device->GL_GetAttribute = ph_GL_GetAttribute;
    device->GL_LoadLibrary = ph_GL_LoadLibrary;
    device->GL_GetProcAddress = ph_GL_GetProcAddress;
#endif /* SDL_VIDEO_OPENGL */

    device->free = ph_DeleteDevice;
    
    return device;
}
static int
GLES_RenderCopy(SDL_Renderer * renderer, SDL_Texture * texture,
                const SDL_Rect * srcrect, const SDL_Rect * dstrect)
{

    GLES_RenderData *data = (GLES_RenderData *) renderer->driverdata;
    GLES_TextureData *texturedata = (GLES_TextureData *) texture->driverdata;
    int minx, miny, maxx, maxy;
    GLfloat minu, maxu, minv, maxv;
    int i;
    void *temp_buffer;          /* used for reformatting dirty rect pixels */
    void *temp_ptr;

    data->glEnable(GL_TEXTURE_2D);

    if (texturedata->dirty.list) {
        SDL_DirtyRect *dirty;
        void *pixels;
        int bpp = SDL_BYTESPERPIXEL(texture->format);
        int pitch = texturedata->pitch;

        SetupTextureUpdate(data, texture, pitch);

        data->glBindTexture(texturedata->type, texturedata->texture);
        for (dirty = texturedata->dirty.list; dirty; dirty = dirty->next) {
            SDL_Rect *rect = &dirty->rect;
            pixels =
                (void *) ((Uint8 *) texturedata->pixels + rect->y * pitch +
                          rect->x * bpp);
            /*      There is no GL_UNPACK_ROW_LENGTH in OpenGLES 
               we must do this reformatting ourselves(!)

               maybe it'd be a good idea to keep a temp buffer around
               for this purpose rather than allocating it each time
             */
            if( rect->x == 0 && rect->w * bpp == pitch ) {
                temp_buffer = pixels; /* Updating whole texture, no need to reformat */
            } else {
                temp_buffer = SDL_malloc(rect->w * rect->h * bpp);
                temp_ptr = temp_buffer;
                for (i = 0; i < rect->h; i++) {
                    SDL_memcpy(temp_ptr, pixels, rect->w * bpp);
                    temp_ptr += rect->w * bpp;
                    pixels += pitch;
                }
            }

            data->glTexSubImage2D(texturedata->type, 0, rect->x, rect->y,
                                  rect->w, rect->h, texturedata->format,
                                  texturedata->formattype, temp_buffer);

            if( temp_buffer != pixels ) {
                SDL_free(temp_buffer);
            }
        }
        SDL_ClearDirtyRects(&texturedata->dirty);
    }

    data->glBindTexture(texturedata->type, texturedata->texture);

    if (texture->modMode) {
        data->glColor4f((GLfloat) texture->r * inv255f,
                        (GLfloat) texture->g * inv255f,
                        (GLfloat) texture->b * inv255f,
                        (GLfloat) texture->a * inv255f);
    } else {
        data->glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    }

    GLES_SetBlendMode(data, texture->blendMode, 0);

    switch (texture->scaleMode) {
    case SDL_SCALEMODE_NONE:
    case SDL_SCALEMODE_FAST:
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MIN_FILTER,
                              GL_NEAREST);
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MAG_FILTER,
                              GL_NEAREST);
        break;
    case SDL_SCALEMODE_SLOW:
    case SDL_SCALEMODE_BEST:
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MIN_FILTER,
                              GL_LINEAR);
        data->glTexParameteri(texturedata->type, GL_TEXTURE_MAG_FILTER,
                              GL_LINEAR);
        break;
    }

    if (data->GL_OES_draw_texture_supported && data->useDrawTexture) {
        /* this code is a little funny because the viewport is upside down vs SDL's coordinate system */
        SDL_Window *window = renderer->window;
        GLint cropRect[4];
        cropRect[0] = srcrect->x;
        cropRect[1] = srcrect->y + srcrect->h;
        cropRect[2] = srcrect->w;
        cropRect[3] = -srcrect->h;
        data->glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_CROP_RECT_OES,
                               cropRect);
        //__android_log_print(ANDROID_LOG_INFO, "libSDL", "GLES_RenderCopy glDrawTexiOES(%d, %d, %d, %d) cropRect %d:%d:%d:%d", dstrect->x, window->display->desktop_mode.h - dstrect->y - dstrect->h, dstrect->w, dstrect->h, cropRect[0], cropRect[1], cropRect[2], cropRect[3]);
        data->glDrawTexiOES(dstrect->x,
#if SDL_VIDEO_RENDER_RESIZE
                            window->display->desktop_mode.h - dstrect->y - dstrect->h,
#else
                            window->h - dstrect->y - dstrect->h,
#endif
                            0, dstrect->w, dstrect->h);
    } else {

        minx = dstrect->x;
        miny = dstrect->y;
        maxx = dstrect->x + dstrect->w;
        maxy = dstrect->y + dstrect->h;

        minu = (GLfloat) srcrect->x / texture->w;
        minu *= texturedata->texw;
        maxu = (GLfloat) (srcrect->x + srcrect->w) / texture->w;
        maxu *= texturedata->texw;
        minv = (GLfloat) srcrect->y / texture->h;
        minv *= texturedata->texh;
        maxv = (GLfloat) (srcrect->y + srcrect->h) / texture->h;
        maxv *= texturedata->texh;

        GLshort vertices[8];
        GLfloat texCoords[8];

        vertices[0] = minx;
        vertices[1] = miny;
        vertices[2] = maxx;
        vertices[3] = miny;
        vertices[4] = minx;
        vertices[5] = maxy;
        vertices[6] = maxx;
        vertices[7] = maxy;

        texCoords[0] = minu;
        texCoords[1] = minv;
        texCoords[2] = maxu;
        texCoords[3] = minv;
        texCoords[4] = minu;
        texCoords[5] = maxv;
        texCoords[6] = maxu;
        texCoords[7] = maxv;

        data->glVertexPointer(2, GL_SHORT, 0, vertices);
        data->glEnableClientState(GL_VERTEX_ARRAY);
        data->glTexCoordPointer(2, GL_FLOAT, 0, texCoords);
        data->glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        data->glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
        data->glDisableClientState(GL_TEXTURE_COORD_ARRAY);
        data->glDisableClientState(GL_VERTEX_ARRAY);
    }

    data->glDisable(GL_TEXTURE_2D);

    return 0;
}
static SDL_VideoDevice *X11_CreateDevice(int devindex)
{
	SDL_VideoDevice *device = NULL;

	if ( SDL_X11_LoadSymbols() ) {
		/* Initialize all variables that we clean on shutdown */
		device = (SDL_VideoDevice *)SDL_malloc(sizeof(SDL_VideoDevice));
		if ( device ) {
			SDL_memset(device, 0, (sizeof *device));
			device->hidden = (struct SDL_PrivateVideoData *)
					SDL_malloc((sizeof *device->hidden));
			device->gl_data = (struct SDL_PrivateGLData *)
					SDL_malloc((sizeof *device->gl_data));
		}
		if ( (device == NULL) || (device->hidden == NULL) ||
		                         (device->gl_data == NULL) ) {
			SDL_OutOfMemory();
			X11_DeleteDevice(device); /* calls SDL_X11_UnloadSymbols(). */
			return(0);
		}
		SDL_memset(device->hidden, 0, (sizeof *device->hidden));
		SDL_memset(device->gl_data, 0, (sizeof *device->gl_data));

#if SDL_VIDEO_OPENGL_GLX
		device->gl_data->swap_interval = -1;
#endif

		/* Set the driver flags */
		device->handles_any_size = 1;

		/* Set the function pointers */
		device->VideoInit = X11_VideoInit;
		device->ListModes = X11_ListModes;
		device->SetVideoMode = X11_SetVideoMode;
		device->ToggleFullScreen = X11_ToggleFullScreen;
		device->UpdateMouse = X11_UpdateMouse;
#if SDL_VIDEO_DRIVER_X11_XV
		device->CreateYUVOverlay = X11_CreateYUVOverlay;
#endif
		device->SetColors = X11_SetColors;
		device->UpdateRects = NULL;
		device->VideoQuit = X11_VideoQuit;
		device->AllocHWSurface = X11_AllocHWSurface;
		device->CheckHWBlit = NULL;
		device->FillHWRect = NULL;
		device->SetHWColorKey = NULL;
		device->SetHWAlpha = NULL;
		device->LockHWSurface = X11_LockHWSurface;
		device->UnlockHWSurface = X11_UnlockHWSurface;
		device->FlipHWSurface = X11_FlipHWSurface;
		device->FreeHWSurface = X11_FreeHWSurface;
		device->SetGamma = X11_SetVidModeGamma;
		device->GetGamma = X11_GetVidModeGamma;
		device->SetGammaRamp = X11_SetGammaRamp;
		device->GetGammaRamp = NULL;
#if SDL_VIDEO_OPENGL_GLX
		device->GL_LoadLibrary = X11_GL_LoadLibrary;
		device->GL_GetProcAddress = X11_GL_GetProcAddress;
		device->GL_GetAttribute = X11_GL_GetAttribute;
		device->GL_MakeCurrent = X11_GL_MakeCurrent;
		device->GL_SwapBuffers = X11_GL_SwapBuffers;
#endif
		device->SetCaption = X11_SetCaption;
		device->SetIcon = X11_SetIcon;
		device->IconifyWindow = X11_IconifyWindow;
		device->GrabInput = X11_GrabInput;
		device->GetWindowPos = X11_GetWindowPos;
		device->SetWindowPos = X11_SetWindowPos;
		device->IsWindowVisible = X11_IsWindowVisible;
		device->GetMonitorDPI = X11_GetMonitorDPI;
		device->GetMonitorRect = X11_GetMonitorRect;
		device->GetWMInfo = X11_GetWMInfo;
		device->FreeWMCursor = X11_FreeWMCursor;
		device->CreateWMCursor = X11_CreateWMCursor;
		device->ShowWMCursor = X11_ShowWMCursor;
		device->WarpWMCursor = X11_WarpWMCursor;
		device->CheckMouseMode = X11_CheckMouseMode;
		device->InitOSKeymap = X11_InitOSKeymap;
		device->PumpEvents = X11_PumpEvents;

		device->free = X11_DeleteDevice;
	}

	return device;
}