code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
This file is created by : Nitin Jain (nitin.j4@samsung.com)
*/
/* Sample program: Draw a Chess Board by using SDL_CreateSoftwareRenderer API */
#include <stdlib.h>
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Surface *surface;
int done;
void
DrawChessBoard(SDL_Renderer * renderer)
{
int row = 0,column = 0,x = 0;
SDL_Rect rect, darea;
/* Get the Size of drawing surface */
SDL_RenderGetViewport(renderer, &darea);
for( ; row < 8; row++)
{
column = row%2;
x = column;
for( ; column < 4+(row%2); column++)
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0xFF);
rect.w = darea.w/8;
rect.h = darea.h/8;
rect.x = x * rect.w;
rect.y = row * rect.h;
x = x + 2;
SDL_RenderFillRect(renderer, &rect);
}
}
}
void
loop()
{
SDL_Event e;
while (SDL_PollEvent(&e)) {
/* Re-create when window has been resized */
if ((e.type == SDL_WINDOWEVENT) && (e.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)) {
SDL_DestroyRenderer(renderer);
surface = SDL_GetWindowSurface(window);
renderer = SDL_CreateSoftwareRenderer(surface);
/* Clear the rendering surface with the specified color */
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
}
if (e.type == SDL_QUIT) {
done = 1;
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop();
#endif
return;
}
if ((e.type == SDL_KEYDOWN) && (e.key.keysym.sym == SDLK_ESCAPE)) {
done = 1;
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop();
#endif
return;
}
}
DrawChessBoard(renderer);
/* Got everything on rendering surface,
now Update the drawing image on window screen */
SDL_UpdateWindowSurface(window);
}
int
main(int argc, char *argv[])
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL */
if(SDL_Init(SDL_INIT_VIDEO) != 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init fail : %s\n", SDL_GetError());
return 1;
}
/* Create window and renderer for given surface */
window = SDL_CreateWindow("Chess Board", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_RESIZABLE);
if(!window)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Window creation fail : %s\n",SDL_GetError());
return 1;
}
surface = SDL_GetWindowSurface(window);
renderer = SDL_CreateSoftwareRenderer(surface);
if(!renderer)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Render creation for surface fail : %s\n",SDL_GetError());
return 1;
}
/* Clear the rendering surface with the specified color */
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
SDL_RenderClear(renderer);
/* Draw the Image on rendering surface */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_Quit();
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testdrawchessboard.c | C | apache-2.0 | 3,761 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include "SDL_test_common.h"
static SDLTest_CommonState *state;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
int
main(int argc, char *argv[])
{
int i, done;
SDL_Event event;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
/* needed voodoo to allow app to launch via OS X Finder */
if (SDL_strncmp(argv[i], "-psn", 4)==0) {
consumed = 1;
}
if (consumed == 0) {
consumed = -1;
}
if (consumed < 0) {
SDLTest_CommonLogUsage(state, argv[0], NULL);
quit(1);
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
/* Main render loop */
done = 0;
while (!done) {
/* Check for events */
while (SDL_PollEvent(&event)) {
if (event.type == SDL_DROPBEGIN) {
SDL_Log("Drop beginning on window %u", (unsigned int) event.drop.windowID);
} else if (event.type == SDL_DROPCOMPLETE) {
SDL_Log("Drop complete on window %u", (unsigned int) event.drop.windowID);
} else if ((event.type == SDL_DROPFILE) || (event.type == SDL_DROPTEXT)) {
const char *typestr = (event.type == SDL_DROPFILE) ? "File" : "Text";
char *dropped_filedir = event.drop.file;
SDL_Log("%s dropped on window %u: %s", typestr, (unsigned int) event.drop.windowID, dropped_filedir);
/* Normally you'd have to do this, but this is freed in SDLTest_CommonEvent() */
/*SDL_free(dropped_filedir);*/
}
SDLTest_CommonEvent(state, &event, &done);
}
}
quit(0);
/* keep the compiler happy ... */
return(0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testdropfile.c | C | apache-2.0 | 2,924 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL threading code and error handling */
#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"
static int alive = 0;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
int SDLCALL
ThreadFunc(void *data)
{
/* Set the child thread error string */
SDL_SetError("Thread %s (%lu) had a problem: %s",
(char *) data, SDL_ThreadID(), "nevermind");
while (alive) {
SDL_Log("Thread '%s' is alive!\n", (char *) data);
SDL_Delay(1 * 1000);
}
SDL_Log("Child thread error string: %s\n", SDL_GetError());
return (0);
}
int
main(int argc, char *argv[])
{
SDL_Thread *thread;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
/* Set the error value for the main thread */
SDL_SetError("No worries");
alive = 1;
thread = SDL_CreateThread(ThreadFunc, NULL, "#1");
if (thread == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError());
quit(1);
}
SDL_Delay(5 * 1000);
SDL_Log("Waiting for thread #1\n");
alive = 0;
SDL_WaitThread(thread, NULL);
SDL_Log("Main thread error string: %s\n", SDL_GetError());
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testerror.c | C | apache-2.0 | 1,967 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* sanity tests on SDL_rwops.c (usefull for alternative implementations of stdio rwops) */
/* quiet windows compiler warnings */
#define _CRT_NONSTDC_NO_WARNINGS
#include <stdlib.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include "SDL.h"
#include <stdio.h>
/* WARNING ! those 2 files will be destroyed by this test program */
#ifdef __IPHONEOS__
#define FBASENAME1 "../Documents/sdldata1" /* this file will be created during tests */
#define FBASENAME2 "../Documents/sdldata2" /* this file should not exist before starting test */
#else
#define FBASENAME1 "sdldata1" /* this file will be created during tests */
#define FBASENAME2 "sdldata2" /* this file should not exist before starting test */
#endif
#ifndef NULL
#define NULL ((void *)0)
#endif
static void
cleanup(void)
{
unlink(FBASENAME1);
unlink(FBASENAME2);
}
static void
rwops_error_quit(unsigned line, SDL_RWops * rwops)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "testfile.c(%d): failed\n", line);
if (rwops) {
rwops->close(rwops); /* This calls SDL_FreeRW(rwops); */
}
cleanup();
exit(1); /* quit with rwops error (test failed) */
}
#define RWOP_ERR_QUIT(x) rwops_error_quit( __LINE__, (x) )
int
main(int argc, char *argv[])
{
SDL_RWops *rwops = NULL;
char test_buf[30];
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
cleanup();
/* test 1 : basic argument test: all those calls to SDL_RWFromFile should fail */
rwops = SDL_RWFromFile(NULL, NULL);
if (rwops)
RWOP_ERR_QUIT(rwops);
rwops = SDL_RWFromFile(NULL, "ab+");
if (rwops)
RWOP_ERR_QUIT(rwops);
rwops = SDL_RWFromFile(NULL, "sldfkjsldkfj");
if (rwops)
RWOP_ERR_QUIT(rwops);
rwops = SDL_RWFromFile("something", "");
if (rwops)
RWOP_ERR_QUIT(rwops);
rwops = SDL_RWFromFile("something", NULL);
if (rwops)
RWOP_ERR_QUIT(rwops);
SDL_Log("test1 OK\n");
/* test 2 : check that inexistent file is not successfully opened/created when required */
/* modes : r, r+ imply that file MUST exist
modes : a, a+, w, w+ checks that it succeeds (file may not exists)
*/
rwops = SDL_RWFromFile(FBASENAME2, "rb"); /* this file doesn't exist that call must fail */
if (rwops)
RWOP_ERR_QUIT(rwops);
rwops = SDL_RWFromFile(FBASENAME2, "rb+"); /* this file doesn't exist that call must fail */
if (rwops)
RWOP_ERR_QUIT(rwops);
rwops = SDL_RWFromFile(FBASENAME2, "wb");
if (!rwops)
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
unlink(FBASENAME2);
rwops = SDL_RWFromFile(FBASENAME2, "wb+");
if (!rwops)
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
unlink(FBASENAME2);
rwops = SDL_RWFromFile(FBASENAME2, "ab");
if (!rwops)
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
unlink(FBASENAME2);
rwops = SDL_RWFromFile(FBASENAME2, "ab+");
if (!rwops)
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
unlink(FBASENAME2);
SDL_Log("test2 OK\n");
/* test 3 : creation, writing , reading, seeking,
test : w mode, r mode, w+ mode
*/
rwops = SDL_RWFromFile(FBASENAME1, "wb"); /* write only */
if (!rwops)
RWOP_ERR_QUIT(rwops);
if (1 != rwops->write(rwops, "1234567890", 10, 1))
RWOP_ERR_QUIT(rwops);
if (10 != rwops->write(rwops, "1234567890", 1, 10))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->write(rwops, "1234567", 1, 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops); /* we are in write only mode */
rwops->close(rwops);
rwops = SDL_RWFromFile(FBASENAME1, "rb"); /* read mode, file must exists */
if (!rwops)
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (20 != rwops->seek(rwops, -7, RW_SEEK_END))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->read(rwops, test_buf, 1, 7))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "1234567", 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 10, 100))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, -27, RW_SEEK_CUR))
RWOP_ERR_QUIT(rwops);
if (2 != rwops->read(rwops, test_buf, 10, 3))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "12345678901234567890", 20))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->write(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops); /* readonly mode */
rwops->close(rwops);
/* test 3: same with w+ mode */
rwops = SDL_RWFromFile(FBASENAME1, "wb+"); /* write + read + truncation */
if (!rwops)
RWOP_ERR_QUIT(rwops);
if (1 != rwops->write(rwops, "1234567890", 10, 1))
RWOP_ERR_QUIT(rwops);
if (10 != rwops->write(rwops, "1234567890", 1, 10))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->write(rwops, "1234567", 1, 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (1 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops); /* we are in read/write mode */
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (20 != rwops->seek(rwops, -7, RW_SEEK_END))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->read(rwops, test_buf, 1, 7))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "1234567", 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 10, 100))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, -27, RW_SEEK_CUR))
RWOP_ERR_QUIT(rwops);
if (2 != rwops->read(rwops, test_buf, 10, 3))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "12345678901234567890", 20))
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
SDL_Log("test3 OK\n");
/* test 4: same in r+ mode */
rwops = SDL_RWFromFile(FBASENAME1, "rb+"); /* write + read + file must exists, no truncation */
if (!rwops)
RWOP_ERR_QUIT(rwops);
if (1 != rwops->write(rwops, "1234567890", 10, 1))
RWOP_ERR_QUIT(rwops);
if (10 != rwops->write(rwops, "1234567890", 1, 10))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->write(rwops, "1234567", 1, 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (1 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops); /* we are in read/write mode */
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (20 != rwops->seek(rwops, -7, RW_SEEK_END))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->read(rwops, test_buf, 1, 7))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "1234567", 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 10, 100))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, -27, RW_SEEK_CUR))
RWOP_ERR_QUIT(rwops);
if (2 != rwops->read(rwops, test_buf, 10, 3))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "12345678901234567890", 20))
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
SDL_Log("test4 OK\n");
/* test5 : append mode */
rwops = SDL_RWFromFile(FBASENAME1, "ab+"); /* write + read + append */
if (!rwops)
RWOP_ERR_QUIT(rwops);
if (1 != rwops->write(rwops, "1234567890", 10, 1))
RWOP_ERR_QUIT(rwops);
if (10 != rwops->write(rwops, "1234567890", 1, 10))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->write(rwops, "1234567", 1, 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (1 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (20 + 27 != rwops->seek(rwops, -7, RW_SEEK_END))
RWOP_ERR_QUIT(rwops);
if (7 != rwops->read(rwops, test_buf, 1, 7))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "1234567", 7))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 1, 1))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->read(rwops, test_buf, 10, 100))
RWOP_ERR_QUIT(rwops);
if (27 != rwops->seek(rwops, -27, RW_SEEK_CUR))
RWOP_ERR_QUIT(rwops);
if (0 != rwops->seek(rwops, 0L, RW_SEEK_SET))
RWOP_ERR_QUIT(rwops);
if (3 != rwops->read(rwops, test_buf, 10, 3))
RWOP_ERR_QUIT(rwops);
if (SDL_memcmp(test_buf, "123456789012345678901234567123", 30))
RWOP_ERR_QUIT(rwops);
rwops->close(rwops);
SDL_Log("test5 OK\n");
cleanup();
return 0; /* all ok */
}
| YifuLiu/AliOS-Things | components/SDL2/test/testfile.c | C | apache-2.0 | 9,473 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of filesystem functions. */
#include <stdio.h>
#include "SDL.h"
int
main(int argc, char *argv[])
{
char *base_path;
char *pref_path;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_Init(0) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError());
return 1;
}
base_path = SDL_GetBasePath();
if(base_path == NULL){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find base path: %s\n",
SDL_GetError());
} else {
SDL_Log("base path: '%s'\n", base_path);
SDL_free(base_path);
}
pref_path = SDL_GetPrefPath("libsdl", "testfilesystem");
if(pref_path == NULL){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find pref path: %s\n",
SDL_GetError());
} else {
SDL_Log("pref path: '%s'\n", pref_path);
SDL_free(pref_path);
}
pref_path = SDL_GetPrefPath(NULL, "testfilesystem");
if(pref_path == NULL){
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find pref path without organization: %s\n",
SDL_GetError());
} else {
SDL_Log("pref path: '%s'\n", pref_path);
SDL_free(pref_path);
}
SDL_Quit();
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testfilesystem.c | C | apache-2.0 | 1,772 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program to test the SDL game controller routines */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#ifndef SDL_JOYSTICK_DISABLED
#ifdef __IPHONEOS__
#define SCREEN_WIDTH 480
#define SCREEN_HEIGHT 320
#else
#define SCREEN_WIDTH 512
#define SCREEN_HEIGHT 320
#endif
/* This is indexed by SDL_GameControllerButton. */
static const struct { int x; int y; } button_positions[] = {
{387, 167}, /* A */
{431, 132}, /* B */
{342, 132}, /* X */
{389, 101}, /* Y */
{174, 132}, /* BACK */
{233, 132}, /* GUIDE */
{289, 132}, /* START */
{75, 154}, /* LEFTSTICK */
{305, 230}, /* RIGHTSTICK */
{77, 40}, /* LEFTSHOULDER */
{396, 36}, /* RIGHTSHOULDER */
{154, 188}, /* DPAD_UP */
{154, 249}, /* DPAD_DOWN */
{116, 217}, /* DPAD_LEFT */
{186, 217}, /* DPAD_RIGHT */
};
/* This is indexed by SDL_GameControllerAxis. */
static const struct { int x; int y; double angle; } axis_positions[] = {
{74, 153, 270.0}, /* LEFTX */
{74, 153, 0.0}, /* LEFTY */
{306, 231, 270.0}, /* RIGHTX */
{306, 231, 0.0}, /* RIGHTY */
{91, -20, 0.0}, /* TRIGGERLEFT */
{375, -20, 0.0}, /* TRIGGERRIGHT */
};
SDL_Window *window = NULL;
SDL_Renderer *screen = NULL;
SDL_bool retval = SDL_FALSE;
SDL_bool done = SDL_FALSE;
SDL_Texture *background, *button, *axis;
SDL_GameController *gamecontroller;
static SDL_Texture *
LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
{
SDL_Surface *temp = NULL;
SDL_Texture *texture = NULL;
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
} else {
/* Set transparent pixel as the pixel at (0,0) */
if (transparent) {
if (temp->format->BytesPerPixel == 1) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *)temp->pixels);
}
}
texture = SDL_CreateTextureFromSurface(renderer, temp);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
}
}
if (temp) {
SDL_FreeSurface(temp);
}
return texture;
}
static void
UpdateWindowTitle()
{
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);
retval = SDL_FALSE;
done = SDL_FALSE;
if (title) {
SDL_snprintf(title, titlelen, "%s%s", basetitle, name);
SDL_SetWindowTitle(window, title);
SDL_free(title);
}
}
void
loop(void *arg)
{
SDL_Event event;
int i;
/* blank screen, set up for drawing this frame. */
SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE);
SDL_RenderClear(screen);
SDL_RenderCopy(screen, background, NULL, NULL);
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_CONTROLLERDEVICEADDED:
SDL_Log("Game controller device %d added.\n", (int) event.cdevice.which);
if (!gamecontroller) {
gamecontroller = SDL_GameControllerOpen(event.cdevice.which);
if (gamecontroller) {
UpdateWindowTitle();
} else {
SDL_Log("Couldn't open controller: %s\n", SDL_GetError());
}
}
break;
case SDL_CONTROLLERDEVICEREMOVED:
SDL_Log("Game controller device %d removed.\n", (int) event.cdevice.which);
if (gamecontroller && event.cdevice.which == SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gamecontroller))) {
SDL_GameControllerClose(gamecontroller);
gamecontroller = SDL_GameControllerOpen(0);
if (gamecontroller) {
UpdateWindowTitle();
}
}
break;
case SDL_CONTROLLERAXISMOTION:
SDL_Log("Controller axis %s changed to %d\n", SDL_GameControllerGetStringForAxis((SDL_GameControllerAxis)event.caxis.axis), event.caxis.value);
break;
case SDL_CONTROLLERBUTTONDOWN:
case SDL_CONTROLLERBUTTONUP:
SDL_Log("Controller button %s %s\n", SDL_GameControllerGetStringForButton((SDL_GameControllerButton)event.cbutton.button), event.cbutton.state ? "pressed" : "released");
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;
}
}
if (gamecontroller) {
/* Update visual controller state */
for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) {
if (SDL_GameControllerGetButton(gamecontroller, (SDL_GameControllerButton)i) == SDL_PRESSED) {
const SDL_Rect dst = { button_positions[i].x, button_positions[i].y, 50, 50 };
SDL_RenderCopyEx(screen, button, NULL, &dst, 0, NULL, SDL_FLIP_NONE);
}
}
for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) {
const Sint16 deadzone = 8000; /* !!! FIXME: real deadzone */
const Sint16 value = SDL_GameControllerGetAxis(gamecontroller, (SDL_GameControllerAxis)(i));
if (value < -deadzone) {
const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 };
const double angle = axis_positions[i].angle;
SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, SDL_FLIP_NONE);
} else if (value > deadzone) {
const SDL_Rect dst = { axis_positions[i].x, axis_positions[i].y, 50, 50 };
const double angle = axis_positions[i].angle + 180.0;
SDL_RenderCopyEx(screen, axis, NULL, &dst, angle, NULL, SDL_FLIP_NONE);
}
}
/* Update rumble based on trigger state */
{
Uint16 low_frequency_rumble = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_TRIGGERLEFT) * 2;
Uint16 high_frequency_rumble = SDL_GameControllerGetAxis(gamecontroller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) * 2;
SDL_GameControllerRumble(gamecontroller, low_frequency_rumble, high_frequency_rumble, 250);
}
}
SDL_RenderPresent(screen);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
int nController = 0;
char guid[64];
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL (Note: video is required to start event loop) */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER ) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
SDL_GameControllerAddMappingsFromFile("gamecontrollerdb.txt");
/* Print information about the mappings */
if (argv[1] && SDL_strcmp(argv[1], "--mappings") == 0) {
SDL_Log("Supported mappings:\n");
for (i = 0; i < SDL_GameControllerNumMappings(); ++i) {
char *mapping = SDL_GameControllerMappingForIndex(i);
if (mapping) {
SDL_Log("\t%s\n", mapping);
SDL_free(mapping);
}
}
SDL_Log("\n");
}
/* Print information about the controller */
for (i = 0; i < SDL_NumJoysticks(); ++i) {
const char *name;
const char *description;
SDL_JoystickGetGUIDString(SDL_JoystickGetDeviceGUID(i),
guid, sizeof (guid));
if ( SDL_IsGameController(i) ) {
nController++;
name = SDL_GameControllerNameForIndex(i);
switch (SDL_GameControllerTypeForIndex(i)) {
case SDL_CONTROLLER_TYPE_XBOX360:
description = "XBox 360 Controller";
break;
case SDL_CONTROLLER_TYPE_XBOXONE:
description = "XBox One Controller";
break;
case SDL_CONTROLLER_TYPE_PS3:
description = "PS3 Controller";
break;
case SDL_CONTROLLER_TYPE_PS4:
description = "PS4 Controller";
break;
case SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO:
description = "Nintendo Switch Pro Controller";
break;
case SDL_CONTROLLER_TYPE_VIRTUAL:
description = "Virtual Game Controller";
break;
default:
description = "Game Controller";
break;
}
} else {
name = SDL_JoystickNameForIndex(i);
description = "Joystick";
}
SDL_Log("%s %d: %s (guid %s, VID 0x%.4x, PID 0x%.4x, player index = %d)\n",
description, i, name ? name : "Unknown", guid,
SDL_JoystickGetDeviceVendor(i), SDL_JoystickGetDeviceProduct(i), SDL_JoystickGetDevicePlayerIndex(i));
}
SDL_Log("There are %d game controller(s) attached (%d joystick(s))\n", nController, SDL_NumJoysticks());
/* Create a window to display controller state */
window = SDL_CreateWindow("Game Controller Test", 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 2;
}
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 2;
}
SDL_SetRenderDrawColor(screen, 0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE);
SDL_RenderClear(screen);
SDL_RenderPresent(screen);
/* scale for platforms that don't give you the window size you asked for. */
SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT);
background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE);
button = LoadTexture(screen, "button.bmp", SDL_TRUE);
axis = LoadTexture(screen, "axis.bmp", SDL_TRUE);
if (!background || !button || !axis) {
SDL_DestroyRenderer(screen);
SDL_DestroyWindow(window);
return 2;
}
SDL_SetTextureColorMod(button, 10, 255, 21);
SDL_SetTextureColorMod(axis, 10, 255, 21);
/* !!! FIXME: */
/*SDL_RenderSetLogicalSize(screen, background->w, background->h);*/
/* Loop, getting controller events! */
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg(loop, NULL, 0, 1);
#else
while (!done) {
loop(NULL);
}
#endif
SDL_DestroyRenderer(screen);
screen = NULL;
background = NULL;
button = NULL;
axis = NULL;
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
return 0;
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
return 1;
}
#endif
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testgamecontroller.c | C | apache-2.0 | 11,999 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Usage:
* Spacebar to begin recording a gesture on all touches.
* s to save all touches into "./gestureSave"
* l to load all touches from "./gestureSave"
*/
#include "SDL.h"
#include <stdlib.h> /* for exit() */
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test.h"
#include "SDL_test_common.h"
#define WIDTH 640
#define HEIGHT 480
#define BPP 4
/* MUST BE A POWER OF 2! */
#define EVENT_BUF_SIZE 256
#define VERBOSE 0
static SDLTest_CommonState *state;
static SDL_Event events[EVENT_BUF_SIZE];
static int eventWrite;
static int colors[7] = {0xFF,0xFF00,0xFF0000,0xFFFF00,0x00FFFF,0xFF00FF,0xFFFFFF};
static int quitting = 0;
typedef struct
{
float x, y;
} Point;
typedef struct
{
float ang, r;
Point p;
} Knob;
static Knob knob = { 0.0f, 0.1f, { 0.0f, 0.0f } };
static void
setpix(SDL_Surface *screen, float _x, float _y, unsigned int col)
{
Uint32 *pixmem32;
Uint32 colour;
Uint8 r, g, b;
const int x = (int)_x;
const int y = (int)_y;
float a;
if ( (x < 0) || (x >= screen->w) || (y < 0) || (y >= screen->h) ) {
return;
}
pixmem32 = (Uint32 *) screen->pixels + y * screen->pitch / BPP + x;
SDL_memcpy(&colour, pixmem32, screen->format->BytesPerPixel);
SDL_GetRGB(colour,screen->format,&r,&g,&b);
/* r = 0;g = 0; b = 0; */
a = (float) ((col >> 24) & 0xFF);
if (a == 0) {
a = 0xFF; /* Hack, to make things easier. */
}
a = (a == 0.0f) ? 1 : (a / 255.0f);
r = (Uint8) (r * (1 - a) + ((col >> 16) & 0xFF) * a);
g = (Uint8) (g * (1 - a) + ((col >> 8) & 0xFF) * a);
b = (Uint8) (b * (1 - a) + ((col >> 0) & 0xFF) * a);
colour = SDL_MapRGB(screen->format, r, g, b);
*pixmem32 = colour;
}
static void
drawLine(SDL_Surface *screen, float x0, float y0, float x1, float y1, unsigned int col)
{
float t;
for (t = 0; t < 1; t += (float) (1.0f / SDL_max(SDL_fabs(x0 - x1), SDL_fabs(y0 - y1)))) {
setpix(screen, x1 + t * (x0 - x1), y1 + t * (y0 - y1), col);
}
}
static void
drawCircle(SDL_Surface *screen, float x, float y, float r, unsigned int c)
{
float tx,ty, xr;
for (ty = (float) -SDL_fabs(r); ty <= (float) SDL_fabs((int) r); ty++) {
xr = (float) SDL_sqrt(r * r - ty * ty);
if (r > 0) { /* r > 0 ==> filled circle */
for(tx = -xr + 0.5f; tx <= xr - 0.5f; tx++) {
setpix(screen, x + tx, y + ty, c);
}
} else {
setpix(screen, x - xr + 0.5f, y + ty, c);
setpix(screen, x + xr - 0.5f, y + ty, c);
}
}
}
static void
drawKnob(SDL_Surface *screen, const Knob *k)
{
drawCircle(screen, k->p.x * screen->w, k->p.y * screen->h, k->r * screen->w, 0xFFFFFF);
drawCircle(screen, (k->p.x + k->r / 2 * SDL_cosf(k->ang)) * screen->w,
(k->p.y + k->r / 2 * SDL_sinf(k->ang)) * screen->h, k->r / 4 * screen->w, 0);
}
static void
DrawScreen(SDL_Window *window)
{
SDL_Surface *screen = SDL_GetWindowSurface(window);
int i;
if (!screen) {
return;
}
SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 75, 75, 75));
/* draw Touch History */
for (i = eventWrite; i < eventWrite + EVENT_BUF_SIZE; ++i) {
const SDL_Event *event = &events[i & (EVENT_BUF_SIZE - 1)];
const float age = (float)(i - eventWrite) / EVENT_BUF_SIZE;
float x, y;
unsigned int c, col;
if ( (event->type == SDL_FINGERMOTION) ||
(event->type == SDL_FINGERDOWN) ||
(event->type == SDL_FINGERUP) ) {
x = event->tfinger.x;
y = event->tfinger.y;
/* draw the touch: */
c = colors[event->tfinger.fingerId % 7];
col = ((unsigned int) (c * (0.1f + 0.85f))) | (unsigned int) (0xFF * age) << 24;
if (event->type == SDL_FINGERMOTION) {
drawCircle(screen, x * screen->w, y * screen->h, 5, col);
} else if (event->type == SDL_FINGERDOWN) {
drawCircle(screen, x * screen->w, y * screen->h, -10, col);
}
}
}
if (knob.p.x > 0) {
drawKnob(screen, &knob);
}
SDL_UpdateWindowSurface(window);
}
static void
loop(void)
{
SDL_Event event;
SDL_RWops *stream;
int i;
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &quitting);
/* Record _all_ events */
events[eventWrite & (EVENT_BUF_SIZE-1)] = event;
eventWrite++;
switch (event.type) {
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_i: {
for (i = 0; i < SDL_GetNumTouchDevices(); ++i) {
const SDL_TouchID id = SDL_GetTouchDevice(i);
SDL_Log("Fingers Down on device %"SDL_PRIs64": %d", id, SDL_GetNumTouchFingers(id));
}
break;
}
case SDLK_SPACE:
SDL_RecordGesture(-1);
break;
case SDLK_s:
stream = SDL_RWFromFile("gestureSave", "w");
SDL_Log("Wrote %i templates", SDL_SaveAllDollarTemplates(stream));
SDL_RWclose(stream);
break;
case SDLK_l:
stream = SDL_RWFromFile("gestureSave", "r");
SDL_Log("Loaded: %i", SDL_LoadDollarTemplates(-1, stream));
SDL_RWclose(stream);
break;
}
break;
#if VERBOSE
case SDL_FINGERMOTION:
SDL_Log("Finger: %"SDL_PRIs64",x: %f, y: %f",event.tfinger.fingerId,
event.tfinger.x,event.tfinger.y);
break;
case SDL_FINGERDOWN:
SDL_Log("Finger: %"SDL_PRIs64" down - x: %f, y: %f",
event.tfinger.fingerId,event.tfinger.x,event.tfinger.y);
break;
case SDL_FINGERUP:
SDL_Log("Finger: %"SDL_PRIs64" up - x: %f, y: %f",
event.tfinger.fingerId,event.tfinger.x,event.tfinger.y);
break;
#endif
case SDL_MULTIGESTURE:
#if VERBOSE
SDL_Log("Multi Gesture: x = %f, y = %f, dAng = %f, dR = %f",
event.mgesture.x, event.mgesture.y,
event.mgesture.dTheta, event.mgesture.dDist);
SDL_Log("MG: numDownTouch = %i",event.mgesture.numFingers);
#endif
knob.p.x = event.mgesture.x;
knob.p.y = event.mgesture.y;
knob.ang += event.mgesture.dTheta;
knob.r += event.mgesture.dDist;
break;
case SDL_DOLLARGESTURE:
SDL_Log("Gesture %"SDL_PRIs64" performed, error: %f",
event.dgesture.gestureId, event.dgesture.error);
break;
case SDL_DOLLARRECORD:
SDL_Log("Recorded gesture: %"SDL_PRIs64"",event.dgesture.gestureId);
break;
}
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i]) {
DrawScreen(state->windows[i]);
}
}
#ifdef __EMSCRIPTEN__
if (quitting) {
emscripten_cancel_main_loop();
}
#endif
}
int main(int argc, char* argv[])
{
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
state->window_title = "Gesture Test";
state->window_w = WIDTH;
state->window_h = HEIGHT;
state->skip_renderer = SDL_TRUE;
if (!SDLTest_CommonDefaultArgs(state, argc, argv) || !SDLTest_CommonInit(state)) {
SDLTest_CommonQuit(state);
return 1;
}
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!quitting) {
loop();
}
#endif
SDLTest_CommonQuit(state);
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testgesture.c | C | apache-2.0 | 8,458 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "SDL_test_common.h"
#ifdef __MACOS__
#define HAVE_OPENGL
#endif
#ifdef HAVE_OPENGL
#include "SDL_opengl.h"
typedef struct GL_Context
{
#define SDL_PROC(ret,func,params) ret (APIENTRY *func) params;
#include "../src/render/opengl/SDL_glfuncs.h"
#undef SDL_PROC
} GL_Context;
/* Undefine this if you want a flat cube instead of a rainbow cube */
#define SHADED_CUBE
static SDLTest_CommonState *state;
static SDL_GLContext context;
static GL_Context ctx;
static int LoadContext(GL_Context * data)
{
#if SDL_VIDEO_DRIVER_UIKIT
#define __SDL_NOGETPROCADDR__
#elif SDL_VIDEO_DRIVER_ANDROID
#define __SDL_NOGETPROCADDR__
#elif SDL_VIDEO_DRIVER_PANDORA
#define __SDL_NOGETPROCADDR__
#endif
#if defined __SDL_NOGETPROCADDR__
#define SDL_PROC(ret,func,params) data->func=func;
#else
#define SDL_PROC(ret,func,params) \
do { \
data->func = SDL_GL_GetProcAddress(#func); \
if ( ! data->func ) { \
return SDL_SetError("Couldn't load GL function %s: %s", #func, SDL_GetError()); \
} \
} while ( 0 );
#endif /* __SDL_NOGETPROCADDR__ */
#include "../src/render/opengl/SDL_glfuncs.h"
#undef SDL_PROC
return 0;
}
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
if (context) {
/* SDL_GL_MakeCurrent(0, NULL); *//* doesn't do anything */
SDL_GL_DeleteContext(context);
}
SDLTest_CommonQuit(state);
exit(rc);
}
static void
Render()
{
static float color[8][3] = {
{1.0, 1.0, 0.0},
{1.0, 0.0, 0.0},
{0.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 1.0, 1.0},
{1.0, 1.0, 1.0},
{1.0, 0.0, 1.0},
{0.0, 0.0, 1.0}
};
static float cube[8][3] = {
{0.5, 0.5, -0.5},
{0.5, -0.5, -0.5},
{-0.5, -0.5, -0.5},
{-0.5, 0.5, -0.5},
{-0.5, 0.5, 0.5},
{0.5, 0.5, 0.5},
{0.5, -0.5, 0.5},
{-0.5, -0.5, 0.5}
};
/* Do our drawing, too. */
ctx.glClearColor(0.0, 0.0, 0.0, 1.0);
ctx.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ctx.glBegin(GL_QUADS);
#ifdef SHADED_CUBE
ctx.glColor3fv(color[0]);
ctx.glVertex3fv(cube[0]);
ctx.glColor3fv(color[1]);
ctx.glVertex3fv(cube[1]);
ctx.glColor3fv(color[2]);
ctx.glVertex3fv(cube[2]);
ctx.glColor3fv(color[3]);
ctx.glVertex3fv(cube[3]);
ctx.glColor3fv(color[3]);
ctx.glVertex3fv(cube[3]);
ctx.glColor3fv(color[4]);
ctx.glVertex3fv(cube[4]);
ctx.glColor3fv(color[7]);
ctx.glVertex3fv(cube[7]);
ctx.glColor3fv(color[2]);
ctx.glVertex3fv(cube[2]);
ctx.glColor3fv(color[0]);
ctx.glVertex3fv(cube[0]);
ctx.glColor3fv(color[5]);
ctx.glVertex3fv(cube[5]);
ctx.glColor3fv(color[6]);
ctx.glVertex3fv(cube[6]);
ctx.glColor3fv(color[1]);
ctx.glVertex3fv(cube[1]);
ctx.glColor3fv(color[5]);
ctx.glVertex3fv(cube[5]);
ctx.glColor3fv(color[4]);
ctx.glVertex3fv(cube[4]);
ctx.glColor3fv(color[7]);
ctx.glVertex3fv(cube[7]);
ctx.glColor3fv(color[6]);
ctx.glVertex3fv(cube[6]);
ctx.glColor3fv(color[5]);
ctx.glVertex3fv(cube[5]);
ctx.glColor3fv(color[0]);
ctx.glVertex3fv(cube[0]);
ctx.glColor3fv(color[3]);
ctx.glVertex3fv(cube[3]);
ctx.glColor3fv(color[4]);
ctx.glVertex3fv(cube[4]);
ctx.glColor3fv(color[6]);
ctx.glVertex3fv(cube[6]);
ctx.glColor3fv(color[1]);
ctx.glVertex3fv(cube[1]);
ctx.glColor3fv(color[2]);
ctx.glVertex3fv(cube[2]);
ctx.glColor3fv(color[7]);
ctx.glVertex3fv(cube[7]);
#else /* flat cube */
ctx.glColor3f(1.0, 0.0, 0.0);
ctx.glVertex3fv(cube[0]);
ctx.glVertex3fv(cube[1]);
ctx.glVertex3fv(cube[2]);
ctx.glVertex3fv(cube[3]);
ctx.glColor3f(0.0, 1.0, 0.0);
ctx.glVertex3fv(cube[3]);
ctx.glVertex3fv(cube[4]);
ctx.glVertex3fv(cube[7]);
ctx.glVertex3fv(cube[2]);
ctx.glColor3f(0.0, 0.0, 1.0);
ctx.glVertex3fv(cube[0]);
ctx.glVertex3fv(cube[5]);
ctx.glVertex3fv(cube[6]);
ctx.glVertex3fv(cube[1]);
ctx.glColor3f(0.0, 1.0, 1.0);
ctx.glVertex3fv(cube[5]);
ctx.glVertex3fv(cube[4]);
ctx.glVertex3fv(cube[7]);
ctx.glVertex3fv(cube[6]);
ctx.glColor3f(1.0, 1.0, 0.0);
ctx.glVertex3fv(cube[5]);
ctx.glVertex3fv(cube[0]);
ctx.glVertex3fv(cube[3]);
ctx.glVertex3fv(cube[4]);
ctx.glColor3f(1.0, 0.0, 1.0);
ctx.glVertex3fv(cube[6]);
ctx.glVertex3fv(cube[1]);
ctx.glVertex3fv(cube[2]);
ctx.glVertex3fv(cube[7]);
#endif /* SHADED_CUBE */
ctx.glEnd();
ctx.glMatrixMode(GL_MODELVIEW);
ctx.glRotatef(5.0, 1.0, 1.0, 1.0);
}
int
main(int argc, char *argv[])
{
int fsaa, accel;
int value;
int i, done;
SDL_DisplayMode mode;
SDL_Event event;
Uint32 then, now, frames;
int status;
int dw, dh;
int swap_interval = 0;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize parameters */
fsaa = 0;
accel = -1;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
if (SDL_strcasecmp(argv[i], "--fsaa") == 0 && i+1 < argc) {
fsaa = atoi(argv[i+1]);
consumed = 2;
} else if (SDL_strcasecmp(argv[i], "--accel") == 0 && i+1 < argc) {
accel = atoi(argv[i+1]);
consumed = 2;
} else {
consumed = -1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--fsaa n]", "[--accel n]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
/* Set OpenGL parameters */
state->window_flags |= SDL_WINDOW_OPENGL;
state->gl_red_size = 5;
state->gl_green_size = 5;
state->gl_blue_size = 5;
state->gl_depth_size = 16;
state->gl_double_buffer = 1;
if (fsaa) {
state->gl_multisamplebuffers = 1;
state->gl_multisamplesamples = fsaa;
}
if (accel >= 0) {
state->gl_accelerated = accel;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
/* Create OpenGL context */
context = SDL_GL_CreateContext(state->windows[0]);
if (!context) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GL_CreateContext(): %s\n", SDL_GetError());
quit(2);
}
/* Important: call this *after* creating the context */
if (LoadContext(&ctx) < 0) {
SDL_Log("Could not load GL functions\n");
quit(2);
return 0;
}
if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) {
/* try late-swap-tearing first. If not supported, try normal vsync. */
if (SDL_GL_SetSwapInterval(-1) == 0) {
swap_interval = -1;
} else {
SDL_GL_SetSwapInterval(1);
swap_interval = 1;
}
} else {
SDL_GL_SetSwapInterval(0); /* disable vsync. */
swap_interval = 0;
}
SDL_GetCurrentDisplayMode(0, &mode);
SDL_Log("Screen BPP : %d\n", SDL_BITSPERPIXEL(mode.format));
SDL_Log("Swap Interval : %d\n", SDL_GL_GetSwapInterval());
SDL_GetWindowSize(state->windows[0], &dw, &dh);
SDL_Log("Window Size : %d,%d\n", dw, dh);
SDL_GL_GetDrawableSize(state->windows[0], &dw, &dh);
SDL_Log("Draw Size : %d,%d\n", dw, dh);
SDL_Log("\n");
SDL_Log("Vendor : %s\n", ctx.glGetString(GL_VENDOR));
SDL_Log("Renderer : %s\n", ctx.glGetString(GL_RENDERER));
SDL_Log("Version : %s\n", ctx.glGetString(GL_VERSION));
SDL_Log("Extensions : %s\n", ctx.glGetString(GL_EXTENSIONS));
SDL_Log("\n");
status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_RED_SIZE: %s\n", SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_GREEN_SIZE: %s\n", SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_BLUE_SIZE: %s\n", SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", 16, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_DEPTH_SIZE: %s\n", SDL_GetError());
}
if (fsaa) {
status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
if (!status) {
SDL_Log("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
if (!status) {
SDL_Log("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n",
SDL_GetError());
}
}
if (accel >= 0) {
status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
if (!status) {
SDL_Log("SDL_GL_ACCELERATED_VISUAL: requested %d, got %d\n", accel,
value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n",
SDL_GetError());
}
}
/* Set rendering settings */
ctx.glMatrixMode(GL_PROJECTION);
ctx.glLoadIdentity();
ctx.glOrtho(-2.0, 2.0, -2.0, 2.0, -20.0, 20.0);
ctx.glMatrixMode(GL_MODELVIEW);
ctx.glLoadIdentity();
ctx.glEnable(GL_DEPTH_TEST);
ctx.glDepthFunc(GL_LESS);
ctx.glShadeModel(GL_SMOOTH);
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
while (!done) {
SDL_bool update_swap_interval = SDL_FALSE;
/* Check for events */
++frames;
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_o) {
swap_interval--;
update_swap_interval = SDL_TRUE;
} else if (event.key.keysym.sym == SDLK_p) {
swap_interval++;
update_swap_interval = SDL_TRUE;
}
}
}
if (update_swap_interval) {
SDL_Log("Swap interval to be set to %d\n", swap_interval);
}
for (i = 0; i < state->num_windows; ++i) {
int w, h;
if (state->windows[i] == NULL)
continue;
SDL_GL_MakeCurrent(state->windows[i], context);
if (update_swap_interval) {
SDL_GL_SetSwapInterval(swap_interval);
}
SDL_GL_GetDrawableSize(state->windows[i], &w, &h);
ctx.glViewport(0, 0, w, h);
Render();
SDL_GL_SwapWindow(state->windows[i]);
}
}
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
SDL_Log("%2.2f frames per second\n",
((double) frames * 1000) / (now - then));
}
quit(0);
return 0;
}
#else /* HAVE_OPENGL */
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No OpenGL support on this system\n");
return 1;
}
#endif /* HAVE_OPENGL */
| YifuLiu/AliOS-Things | components/SDL2/test/testgl2.c | C | apache-2.0 | 12,691 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "SDL_test_common.h"
#if defined(__IPHONEOS__) || defined(__ANDROID__)
#define HAVE_OPENGLES
#endif
#ifdef HAVE_OPENGLES
#include "SDL_opengles.h"
static SDLTest_CommonState *state;
static SDL_GLContext *context = NULL;
static int depth = 16;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
int i;
if (context != NULL) {
for (i = 0; i < state->num_windows; i++) {
if (context[i]) {
SDL_GL_DeleteContext(context[i]);
}
}
SDL_free(context);
}
SDLTest_CommonQuit(state);
exit(rc);
}
static void
Render()
{
static GLubyte color[8][4] = { {255, 0, 0, 0},
{255, 0, 0, 255},
{0, 255, 0, 255},
{0, 255, 0, 255},
{0, 255, 0, 255},
{255, 255, 255, 255},
{255, 0, 255, 255},
{0, 0, 255, 255}
};
static GLfloat cube[8][3] = { {0.5, 0.5, -0.5},
{0.5f, -0.5f, -0.5f},
{-0.5f, -0.5f, -0.5f},
{-0.5f, 0.5f, -0.5f},
{-0.5f, 0.5f, 0.5f},
{0.5f, 0.5f, 0.5f},
{0.5f, -0.5f, 0.5f},
{-0.5f, -0.5f, 0.5f}
};
static GLubyte indices[36] = { 0, 3, 4,
4, 5, 0,
0, 5, 6,
6, 1, 0,
6, 7, 2,
2, 1, 6,
7, 4, 3,
3, 2, 7,
5, 4, 7,
7, 6, 5,
2, 3, 1,
3, 0, 1
};
/* Do our drawing, too. */
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Draw the cube */
glColorPointer(4, GL_UNSIGNED_BYTE, 0, color);
glEnableClientState(GL_COLOR_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, cube);
glEnableClientState(GL_VERTEX_ARRAY);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, indices);
glMatrixMode(GL_MODELVIEW);
glRotatef(5.0, 1.0, 1.0, 1.0);
}
int
main(int argc, char *argv[])
{
int fsaa, accel;
int value;
int i, done;
SDL_DisplayMode mode;
SDL_Event event;
Uint32 then, now, frames;
int status;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize parameters */
fsaa = 0;
accel = 0;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
if (SDL_strcasecmp(argv[i], "--fsaa") == 0) {
++fsaa;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--accel") == 0) {
++accel;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) {
i++;
if (!argv[i]) {
consumed = -1;
} else {
depth = SDL_atoi(argv[i]);
consumed = 1;
}
} else {
consumed = -1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--fsaa]", "[--accel]", "[--zdepth %d]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
/* Set OpenGL parameters */
state->window_flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS;
state->gl_red_size = 5;
state->gl_green_size = 5;
state->gl_blue_size = 5;
state->gl_depth_size = depth;
state->gl_major_version = 1;
state->gl_minor_version = 1;
state->gl_profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
if (fsaa) {
state->gl_multisamplebuffers=1;
state->gl_multisamplesamples=fsaa;
}
if (accel) {
state->gl_accelerated=1;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
context = (SDL_GLContext *)SDL_calloc(state->num_windows, sizeof(context));
if (context == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
quit(2);
}
/* Create OpenGL ES contexts */
for (i = 0; i < state->num_windows; i++) {
context[i] = SDL_GL_CreateContext(state->windows[i]);
if (!context[i]) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_GL_CreateContext(): %s\n", SDL_GetError());
quit(2);
}
}
if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) {
SDL_GL_SetSwapInterval(1);
} else {
SDL_GL_SetSwapInterval(0);
}
SDL_GetCurrentDisplayMode(0, &mode);
SDL_Log("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format));
SDL_Log("\n");
SDL_Log("Vendor : %s\n", glGetString(GL_VENDOR));
SDL_Log("Renderer : %s\n", glGetString(GL_RENDERER));
SDL_Log("Version : %s\n", glGetString(GL_VERSION));
SDL_Log("Extensions : %s\n", glGetString(GL_EXTENSIONS));
SDL_Log("\n");
status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_RED_SIZE: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_GREEN_SIZE: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_BLUE_SIZE: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_DEPTH_SIZE: %s\n",
SDL_GetError());
}
if (fsaa) {
status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
if (!status) {
SDL_Log("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
if (!status) {
SDL_Log("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n",
SDL_GetError());
}
}
if (accel) {
status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
if (!status) {
SDL_Log("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n",
SDL_GetError());
}
}
/* Set rendering settings for each context */
for (i = 0; i < state->num_windows; ++i) {
float aspectAdjust;
status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
if (status) {
SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
/* Continue for next window */
continue;
}
aspectAdjust = (4.0f / 3.0f) / ((float)state->window_w / state->window_h);
glViewport(0, 0, state->window_w, state->window_h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(-2.0, 2.0, -2.0 * aspectAdjust, 2.0 * aspectAdjust, -20.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glShadeModel(GL_SMOOTH);
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
while (!done) {
/* Check for events */
++frames;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_RESIZED:
for (i = 0; i < state->num_windows; ++i) {
if (event.window.windowID == SDL_GetWindowID(state->windows[i])) {
status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
if (status) {
SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
break;
}
/* Change view port to the new window dimensions */
glViewport(0, 0, event.window.data1, event.window.data2);
/* Update window content */
Render();
SDL_GL_SwapWindow(state->windows[i]);
break;
}
}
break;
}
}
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
if (status) {
SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
/* Continue for next window */
continue;
}
Render();
SDL_GL_SwapWindow(state->windows[i]);
}
}
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
SDL_Log("%2.2f frames per second\n",
((double) frames * 1000) / (now - then));
}
#if !defined(__ANDROID__)
quit(0);
#endif
return 0;
}
#else /* HAVE_OPENGLES */
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No OpenGL ES support on this system\n");
return 1;
}
#endif /* HAVE_OPENGLES */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testgles.c | C | apache-2.0 | 10,867 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
#if defined(__IPHONEOS__) || defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__NACL__) \
|| defined(__WINDOWS__) || defined(__LINUX__)
#define HAVE_OPENGLES2
#endif
#ifdef HAVE_OPENGLES2
#include "SDL_opengles2.h"
typedef struct GLES2_Context
{
#define SDL_PROC(ret,func,params) ret (APIENTRY *func) params;
#include "../src/render/opengles2/SDL_gles2funcs.h"
#undef SDL_PROC
} GLES2_Context;
static SDLTest_CommonState *state;
static SDL_GLContext *context = NULL;
static int depth = 16;
static GLES2_Context ctx;
static int LoadContext(GLES2_Context * data)
{
#if SDL_VIDEO_DRIVER_UIKIT
#define __SDL_NOGETPROCADDR__
#elif SDL_VIDEO_DRIVER_ANDROID
#define __SDL_NOGETPROCADDR__
#elif SDL_VIDEO_DRIVER_PANDORA
#define __SDL_NOGETPROCADDR__
#endif
#if defined __SDL_NOGETPROCADDR__
#define SDL_PROC(ret,func,params) data->func=func;
#else
#define SDL_PROC(ret,func,params) \
do { \
data->func = SDL_GL_GetProcAddress(#func); \
if ( ! data->func ) { \
return SDL_SetError("Couldn't load GLES2 function %s: %s", #func, SDL_GetError()); \
} \
} while ( 0 );
#endif /* __SDL_NOGETPROCADDR__ */
#include "../src/render/opengles2/SDL_gles2funcs.h"
#undef SDL_PROC
return 0;
}
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
int i;
if (context != NULL) {
for (i = 0; i < state->num_windows; i++) {
if (context[i]) {
SDL_GL_DeleteContext(context[i]);
}
}
SDL_free(context);
}
SDLTest_CommonQuit(state);
exit(rc);
}
#define GL_CHECK(x) \
x; \
{ \
GLenum glError = ctx.glGetError(); \
if(glError != GL_NO_ERROR) { \
SDL_Log("glGetError() = %i (0x%.8x) at line %i\n", glError, glError, __LINE__); \
quit(1); \
} \
}
/*
* Simulates desktop's glRotatef. The matrix is returned in column-major
* order.
*/
static void
rotate_matrix(float angle, float x, float y, float z, float *r)
{
float radians, c, s, c1, u[3], length;
int i, j;
radians = (float)(angle * M_PI) / 180.0f;
c = SDL_cosf(radians);
s = SDL_sinf(radians);
c1 = 1.0f - SDL_cosf(radians);
length = (float)SDL_sqrt(x * x + y * y + z * z);
u[0] = x / length;
u[1] = y / length;
u[2] = z / length;
for (i = 0; i < 16; i++) {
r[i] = 0.0;
}
r[15] = 1.0;
for (i = 0; i < 3; i++) {
r[i * 4 + (i + 1) % 3] = u[(i + 2) % 3] * s;
r[i * 4 + (i + 2) % 3] = -u[(i + 1) % 3] * s;
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
r[i * 4 + j] += c1 * u[i] * u[j] + (i == j ? c : 0.0f);
}
}
}
/*
* Simulates gluPerspectiveMatrix
*/
static void
perspective_matrix(float fovy, float aspect, float znear, float zfar, float *r)
{
int i;
float f;
f = 1.0f/SDL_tanf(fovy * 0.5f);
for (i = 0; i < 16; i++) {
r[i] = 0.0;
}
r[0] = f / aspect;
r[5] = f;
r[10] = (znear + zfar) / (znear - zfar);
r[11] = -1.0f;
r[14] = (2.0f * znear * zfar) / (znear - zfar);
r[15] = 0.0f;
}
/*
* Multiplies lhs by rhs and writes out to r. All matrices are 4x4 and column
* major. In-place multiplication is supported.
*/
static void
multiply_matrix(float *lhs, float *rhs, float *r)
{
int i, j, k;
float tmp[16];
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
tmp[j * 4 + i] = 0.0;
for (k = 0; k < 4; k++) {
tmp[j * 4 + i] += lhs[k * 4 + i] * rhs[j * 4 + k];
}
}
}
for (i = 0; i < 16; i++) {
r[i] = tmp[i];
}
}
/*
* Create shader, load in source, compile, dump debug as necessary.
*
* shader: Pointer to return created shader ID.
* source: Passed-in shader source code.
* shader_type: Passed to GL, e.g. GL_VERTEX_SHADER.
*/
void
process_shader(GLuint *shader, const char * source, GLint shader_type)
{
GLint status = GL_FALSE;
const char *shaders[1] = { NULL };
char buffer[1024];
GLsizei length;
/* Create shader and load into GL. */
*shader = GL_CHECK(ctx.glCreateShader(shader_type));
shaders[0] = source;
GL_CHECK(ctx.glShaderSource(*shader, 1, shaders, NULL));
/* Clean up shader source. */
shaders[0] = NULL;
/* Try compiling the shader. */
GL_CHECK(ctx.glCompileShader(*shader));
GL_CHECK(ctx.glGetShaderiv(*shader, GL_COMPILE_STATUS, &status));
/* Dump debug info (source and log) if compilation failed. */
if(status != GL_TRUE) {
ctx.glGetProgramInfoLog(*shader, sizeof(buffer), &length, &buffer[0]);
buffer[length] = '\0';
SDL_Log("Shader compilation failed: %s", buffer);fflush(stderr);
quit(-1);
}
}
/* 3D data. Vertex range -0.5..0.5 in all axes.
* Z -0.5 is near, 0.5 is far. */
const float _vertices[] =
{
/* Front face. */
/* Bottom left */
-0.5, 0.5, -0.5,
0.5, -0.5, -0.5,
-0.5, -0.5, -0.5,
/* Top right */
-0.5, 0.5, -0.5,
0.5, 0.5, -0.5,
0.5, -0.5, -0.5,
/* Left face */
/* Bottom left */
-0.5, 0.5, 0.5,
-0.5, -0.5, -0.5,
-0.5, -0.5, 0.5,
/* Top right */
-0.5, 0.5, 0.5,
-0.5, 0.5, -0.5,
-0.5, -0.5, -0.5,
/* Top face */
/* Bottom left */
-0.5, 0.5, 0.5,
0.5, 0.5, -0.5,
-0.5, 0.5, -0.5,
/* Top right */
-0.5, 0.5, 0.5,
0.5, 0.5, 0.5,
0.5, 0.5, -0.5,
/* Right face */
/* Bottom left */
0.5, 0.5, -0.5,
0.5, -0.5, 0.5,
0.5, -0.5, -0.5,
/* Top right */
0.5, 0.5, -0.5,
0.5, 0.5, 0.5,
0.5, -0.5, 0.5,
/* Back face */
/* Bottom left */
0.5, 0.5, 0.5,
-0.5, -0.5, 0.5,
0.5, -0.5, 0.5,
/* Top right */
0.5, 0.5, 0.5,
-0.5, 0.5, 0.5,
-0.5, -0.5, 0.5,
/* Bottom face */
/* Bottom left */
-0.5, -0.5, -0.5,
0.5, -0.5, 0.5,
-0.5, -0.5, 0.5,
/* Top right */
-0.5, -0.5, -0.5,
0.5, -0.5, -0.5,
0.5, -0.5, 0.5,
};
const float _colors[] =
{
/* Front face */
/* Bottom left */
1.0, 0.0, 0.0, /* red */
0.0, 0.0, 1.0, /* blue */
0.0, 1.0, 0.0, /* green */
/* Top right */
1.0, 0.0, 0.0, /* red */
1.0, 1.0, 0.0, /* yellow */
0.0, 0.0, 1.0, /* blue */
/* Left face */
/* Bottom left */
1.0, 1.0, 1.0, /* white */
0.0, 1.0, 0.0, /* green */
0.0, 1.0, 1.0, /* cyan */
/* Top right */
1.0, 1.0, 1.0, /* white */
1.0, 0.0, 0.0, /* red */
0.0, 1.0, 0.0, /* green */
/* Top face */
/* Bottom left */
1.0, 1.0, 1.0, /* white */
1.0, 1.0, 0.0, /* yellow */
1.0, 0.0, 0.0, /* red */
/* Top right */
1.0, 1.0, 1.0, /* white */
0.0, 0.0, 0.0, /* black */
1.0, 1.0, 0.0, /* yellow */
/* Right face */
/* Bottom left */
1.0, 1.0, 0.0, /* yellow */
1.0, 0.0, 1.0, /* magenta */
0.0, 0.0, 1.0, /* blue */
/* Top right */
1.0, 1.0, 0.0, /* yellow */
0.0, 0.0, 0.0, /* black */
1.0, 0.0, 1.0, /* magenta */
/* Back face */
/* Bottom left */
0.0, 0.0, 0.0, /* black */
0.0, 1.0, 1.0, /* cyan */
1.0, 0.0, 1.0, /* magenta */
/* Top right */
0.0, 0.0, 0.0, /* black */
1.0, 1.0, 1.0, /* white */
0.0, 1.0, 1.0, /* cyan */
/* Bottom face */
/* Bottom left */
0.0, 1.0, 0.0, /* green */
1.0, 0.0, 1.0, /* magenta */
0.0, 1.0, 1.0, /* cyan */
/* Top right */
0.0, 1.0, 0.0, /* green */
0.0, 0.0, 1.0, /* blue */
1.0, 0.0, 1.0, /* magenta */
};
const char* _shader_vert_src =
" attribute vec4 av4position; "
" attribute vec3 av3color; "
" uniform mat4 mvp; "
" varying vec3 vv3color; "
" void main() { "
" vv3color = av3color; "
" gl_Position = mvp * av4position; "
" } ";
const char* _shader_frag_src =
" precision lowp float; "
" varying vec3 vv3color; "
" void main() { "
" gl_FragColor = vec4(vv3color, 1.0); "
" } ";
typedef struct shader_data
{
GLuint shader_program, shader_frag, shader_vert;
GLint attr_position;
GLint attr_color, attr_mvp;
int angle_x, angle_y, angle_z;
} shader_data;
static void
Render(unsigned int width, unsigned int height, shader_data* data)
{
float matrix_rotate[16], matrix_modelview[16], matrix_perspective[16], matrix_mvp[16];
/*
* Do some rotation with Euler angles. It is not a fixed axis as
* quaterions would be, but the effect is cool.
*/
rotate_matrix((float)data->angle_x, 1.0f, 0.0f, 0.0f, matrix_modelview);
rotate_matrix((float)data->angle_y, 0.0f, 1.0f, 0.0f, matrix_rotate);
multiply_matrix(matrix_rotate, matrix_modelview, matrix_modelview);
rotate_matrix((float)data->angle_z, 0.0f, 1.0f, 0.0f, matrix_rotate);
multiply_matrix(matrix_rotate, matrix_modelview, matrix_modelview);
/* Pull the camera back from the cube */
matrix_modelview[14] -= 2.5;
perspective_matrix(45.0f, (float)width/height, 0.01f, 100.0f, matrix_perspective);
multiply_matrix(matrix_perspective, matrix_modelview, matrix_mvp);
GL_CHECK(ctx.glUniformMatrix4fv(data->attr_mvp, 1, GL_FALSE, matrix_mvp));
data->angle_x += 3;
data->angle_y += 2;
data->angle_z += 1;
if(data->angle_x >= 360) data->angle_x -= 360;
if(data->angle_x < 0) data->angle_x += 360;
if(data->angle_y >= 360) data->angle_y -= 360;
if(data->angle_y < 0) data->angle_y += 360;
if(data->angle_z >= 360) data->angle_z -= 360;
if(data->angle_z < 0) data->angle_z += 360;
GL_CHECK(ctx.glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));
GL_CHECK(ctx.glDrawArrays(GL_TRIANGLES, 0, 36));
}
int done;
Uint32 frames;
shader_data *datas;
void loop()
{
SDL_Event event;
int i;
int status;
/* Check for events */
++frames;
while (SDL_PollEvent(&event) && !done) {
switch (event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_RESIZED:
for (i = 0; i < state->num_windows; ++i) {
if (event.window.windowID == SDL_GetWindowID(state->windows[i])) {
int w, h;
status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
if (status) {
SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
break;
}
/* Change view port to the new window dimensions */
SDL_GL_GetDrawableSize(state->windows[i], &w, &h);
ctx.glViewport(0, 0, w, h);
state->window_w = event.window.data1;
state->window_h = event.window.data2;
/* Update window content */
Render(event.window.data1, event.window.data2, &datas[i]);
SDL_GL_SwapWindow(state->windows[i]);
break;
}
}
break;
}
}
SDLTest_CommonEvent(state, &event, &done);
}
if (!done) {
for (i = 0; i < state->num_windows; ++i) {
status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
if (status) {
SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
/* Continue for next window */
continue;
}
Render(state->window_w, state->window_h, &datas[i]);
SDL_GL_SwapWindow(state->windows[i]);
}
}
#ifdef __EMSCRIPTEN__
else {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int fsaa, accel;
int value;
int i;
SDL_DisplayMode mode;
Uint32 then, now;
int status;
shader_data *data;
/* Initialize parameters */
fsaa = 0;
accel = 0;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
if (SDL_strcasecmp(argv[i], "--fsaa") == 0) {
++fsaa;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--accel") == 0) {
++accel;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--zdepth") == 0) {
i++;
if (!argv[i]) {
consumed = -1;
} else {
depth = SDL_atoi(argv[i]);
consumed = 1;
}
} else {
consumed = -1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--fsaa]", "[--accel]", "[--zdepth %d]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
/* Set OpenGL parameters */
state->window_flags |= SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS;
state->gl_red_size = 5;
state->gl_green_size = 5;
state->gl_blue_size = 5;
state->gl_depth_size = depth;
state->gl_major_version = 2;
state->gl_minor_version = 0;
state->gl_profile_mask = SDL_GL_CONTEXT_PROFILE_ES;
if (fsaa) {
state->gl_multisamplebuffers=1;
state->gl_multisamplesamples=fsaa;
}
if (accel) {
state->gl_accelerated=1;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
return 0;
}
context = (SDL_GLContext *)SDL_calloc(state->num_windows, sizeof(context));
if (context == NULL) {
SDL_Log("Out of memory!\n");
quit(2);
}
/* Create OpenGL ES contexts */
for (i = 0; i < state->num_windows; i++) {
context[i] = SDL_GL_CreateContext(state->windows[i]);
if (!context[i]) {
SDL_Log("SDL_GL_CreateContext(): %s\n", SDL_GetError());
quit(2);
}
}
/* Important: call this *after* creating the context */
if (LoadContext(&ctx) < 0) {
SDL_Log("Could not load GLES2 functions\n");
quit(2);
return 0;
}
if (state->render_flags & SDL_RENDERER_PRESENTVSYNC) {
SDL_GL_SetSwapInterval(1);
} else {
SDL_GL_SetSwapInterval(0);
}
SDL_GetCurrentDisplayMode(0, &mode);
SDL_Log("Screen bpp: %d\n", SDL_BITSPERPIXEL(mode.format));
SDL_Log("\n");
SDL_Log("Vendor : %s\n", ctx.glGetString(GL_VENDOR));
SDL_Log("Renderer : %s\n", ctx.glGetString(GL_RENDERER));
SDL_Log("Version : %s\n", ctx.glGetString(GL_VERSION));
SDL_Log("Extensions : %s\n", ctx.glGetString(GL_EXTENSIONS));
SDL_Log("\n");
status = SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_RED_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_Log( "Failed to get SDL_GL_RED_SIZE: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_GREEN_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_Log( "Failed to get SDL_GL_GREEN_SIZE: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_BLUE_SIZE: requested %d, got %d\n", 5, value);
} else {
SDL_Log( "Failed to get SDL_GL_BLUE_SIZE: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &value);
if (!status) {
SDL_Log("SDL_GL_DEPTH_SIZE: requested %d, got %d\n", depth, value);
} else {
SDL_Log( "Failed to get SDL_GL_DEPTH_SIZE: %s\n",
SDL_GetError());
}
if (fsaa) {
status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &value);
if (!status) {
SDL_Log("SDL_GL_MULTISAMPLEBUFFERS: requested 1, got %d\n", value);
} else {
SDL_Log( "Failed to get SDL_GL_MULTISAMPLEBUFFERS: %s\n",
SDL_GetError());
}
status = SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &value);
if (!status) {
SDL_Log("SDL_GL_MULTISAMPLESAMPLES: requested %d, got %d\n", fsaa,
value);
} else {
SDL_Log( "Failed to get SDL_GL_MULTISAMPLESAMPLES: %s\n",
SDL_GetError());
}
}
if (accel) {
status = SDL_GL_GetAttribute(SDL_GL_ACCELERATED_VISUAL, &value);
if (!status) {
SDL_Log("SDL_GL_ACCELERATED_VISUAL: requested 1, got %d\n", value);
} else {
SDL_Log( "Failed to get SDL_GL_ACCELERATED_VISUAL: %s\n",
SDL_GetError());
}
}
datas = (shader_data *)SDL_calloc(state->num_windows, sizeof(shader_data));
/* Set rendering settings for each context */
for (i = 0; i < state->num_windows; ++i) {
int w, h;
status = SDL_GL_MakeCurrent(state->windows[i], context[i]);
if (status) {
SDL_Log("SDL_GL_MakeCurrent(): %s\n", SDL_GetError());
/* Continue for next window */
continue;
}
SDL_GL_GetDrawableSize(state->windows[i], &w, &h);
ctx.glViewport(0, 0, w, h);
data = &datas[i];
data->angle_x = 0; data->angle_y = 0; data->angle_z = 0;
/* Shader Initialization */
process_shader(&data->shader_vert, _shader_vert_src, GL_VERTEX_SHADER);
process_shader(&data->shader_frag, _shader_frag_src, GL_FRAGMENT_SHADER);
/* Create shader_program (ready to attach shaders) */
data->shader_program = GL_CHECK(ctx.glCreateProgram());
/* Attach shaders and link shader_program */
GL_CHECK(ctx.glAttachShader(data->shader_program, data->shader_vert));
GL_CHECK(ctx.glAttachShader(data->shader_program, data->shader_frag));
GL_CHECK(ctx.glLinkProgram(data->shader_program));
/* Get attribute locations of non-fixed attributes like color and texture coordinates. */
data->attr_position = GL_CHECK(ctx.glGetAttribLocation(data->shader_program, "av4position"));
data->attr_color = GL_CHECK(ctx.glGetAttribLocation(data->shader_program, "av3color"));
/* Get uniform locations */
data->attr_mvp = GL_CHECK(ctx.glGetUniformLocation(data->shader_program, "mvp"));
GL_CHECK(ctx.glUseProgram(data->shader_program));
/* Enable attributes for position, color and texture coordinates etc. */
GL_CHECK(ctx.glEnableVertexAttribArray(data->attr_position));
GL_CHECK(ctx.glEnableVertexAttribArray(data->attr_color));
/* Populate attributes for position, color and texture coordinates etc. */
GL_CHECK(ctx.glVertexAttribPointer(data->attr_position, 3, GL_FLOAT, GL_FALSE, 0, _vertices));
GL_CHECK(ctx.glVertexAttribPointer(data->attr_color, 3, GL_FLOAT, GL_FALSE, 0, _colors));
GL_CHECK(ctx.glEnable(GL_CULL_FACE));
GL_CHECK(ctx.glEnable(GL_DEPTH_TEST));
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
SDL_Log("%2.2f frames per second\n",
((double) frames * 1000) / (now - then));
}
#if !defined(__ANDROID__) && !defined(__NACL__)
quit(0);
#endif
return 0;
}
#else /* HAVE_OPENGLES2 */
int
main(int argc, char *argv[])
{
SDL_Log("No OpenGL ES support on this system\n");
return 1;
}
#endif /* HAVE_OPENGLES2 */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testgles2.c | C | apache-2.0 | 20,569 |
/*
Copyright (c) 2008, Edgar Simo Serra
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Simple Directmedia Layer (SDL) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* includes
*/
#include <stdlib.h>
#include <string.h> /* strstr */
#include <ctype.h> /* isdigit */
#include "SDL.h"
#ifndef SDL_HAPTIC_DISABLED
static SDL_Haptic *haptic;
/*
* prototypes
*/
static void abort_execution(void);
static void HapticPrintSupported(SDL_Haptic * haptic);
/**
* @brief The entry point of this force feedback demo.
* @param[in] argc Number of arguments.
* @param[in] argv Array of argc arguments.
*/
int
main(int argc, char **argv)
{
int i;
char *name;
int index;
SDL_HapticEffect efx[9];
int id[9];
int nefx;
unsigned int supported;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
name = NULL;
index = -1;
if (argc > 1) {
name = argv[1];
if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) {
SDL_Log("USAGE: %s [device]\n"
"If device is a two-digit number it'll use it as an index, otherwise\n"
"it'll use it as if it were part of the device's name.\n",
argv[0]);
return 0;
}
i = strlen(name);
if ((i < 3) && isdigit(name[0]) && ((i == 1) || isdigit(name[1]))) {
index = atoi(name);
name = NULL;
}
}
/* Initialize the force feedbackness */
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK |
SDL_INIT_HAPTIC);
SDL_Log("%d Haptic devices detected.\n", SDL_NumHaptics());
if (SDL_NumHaptics() > 0) {
/* We'll just use index or the first force feedback device found */
if (name == NULL) {
i = (index != -1) ? index : 0;
}
/* Try to find matching device */
else {
for (i = 0; i < SDL_NumHaptics(); i++) {
if (strstr(SDL_HapticName(i), name) != NULL)
break;
}
if (i >= SDL_NumHaptics()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to find device matching '%s', aborting.\n",
name);
return 1;
}
}
haptic = SDL_HapticOpen(i);
if (haptic == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create the haptic device: %s\n",
SDL_GetError());
return 1;
}
SDL_Log("Device: %s\n", SDL_HapticName(i));
HapticPrintSupported(haptic);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Haptic devices found!\n");
return 1;
}
/* We only want force feedback errors. */
SDL_ClearError();
/* Create effects. */
memset(&efx, 0, sizeof(efx));
nefx = 0;
supported = SDL_HapticQuery(haptic);
SDL_Log("\nUploading effects\n");
/* First we'll try a SINE effect. */
if (supported & SDL_HAPTIC_SINE) {
SDL_Log(" effect %d: Sine Wave\n", nefx);
efx[nefx].type = SDL_HAPTIC_SINE;
efx[nefx].periodic.period = 1000;
efx[nefx].periodic.magnitude = -0x2000; /* Negative magnitude and ... */
efx[nefx].periodic.phase = 18000; /* ... 180 degrees phase shift => cancel eachother */
efx[nefx].periodic.length = 5000;
efx[nefx].periodic.attack_length = 1000;
efx[nefx].periodic.fade_length = 1000;
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* Now we'll try a SAWTOOTHUP */
if (supported & SDL_HAPTIC_SAWTOOTHUP) {
SDL_Log(" effect %d: Sawtooth Up\n", nefx);
efx[nefx].type = SDL_HAPTIC_SAWTOOTHUP;
efx[nefx].periodic.period = 500;
efx[nefx].periodic.magnitude = 0x5000;
efx[nefx].periodic.length = 5000;
efx[nefx].periodic.attack_length = 1000;
efx[nefx].periodic.fade_length = 1000;
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* Now the classical constant effect. */
if (supported & SDL_HAPTIC_CONSTANT) {
SDL_Log(" effect %d: Constant Force\n", nefx);
efx[nefx].type = SDL_HAPTIC_CONSTANT;
efx[nefx].constant.direction.type = SDL_HAPTIC_POLAR;
efx[nefx].constant.direction.dir[0] = 20000; /* Force comes from the south-west. */
efx[nefx].constant.length = 5000;
efx[nefx].constant.level = 0x6000;
efx[nefx].constant.attack_length = 1000;
efx[nefx].constant.fade_length = 1000;
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* The cute spring effect. */
if (supported & SDL_HAPTIC_SPRING) {
SDL_Log(" effect %d: Condition Spring\n", nefx);
efx[nefx].type = SDL_HAPTIC_SPRING;
efx[nefx].condition.length = 5000;
for (i = 0; i < SDL_HapticNumAxes(haptic); i++) {
efx[nefx].condition.right_sat[i] = 0xFFFF;
efx[nefx].condition.left_sat[i] = 0xFFFF;
efx[nefx].condition.right_coeff[i] = 0x2000;
efx[nefx].condition.left_coeff[i] = 0x2000;
efx[nefx].condition.center[i] = 0x1000; /* Displace the center for it to move. */
}
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* The interesting damper effect. */
if (supported & SDL_HAPTIC_DAMPER) {
SDL_Log(" effect %d: Condition Damper\n", nefx);
efx[nefx].type = SDL_HAPTIC_DAMPER;
efx[nefx].condition.length = 5000;
for (i = 0; i < SDL_HapticNumAxes(haptic); i++) {
efx[nefx].condition.right_sat[i] = 0xFFFF;
efx[nefx].condition.left_sat[i] = 0xFFFF;
efx[nefx].condition.right_coeff[i] = 0x2000;
efx[nefx].condition.left_coeff[i] = 0x2000;
}
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* The pretty awesome inertia effect. */
if (supported & SDL_HAPTIC_INERTIA) {
SDL_Log(" effect %d: Condition Inertia\n", nefx);
efx[nefx].type = SDL_HAPTIC_INERTIA;
efx[nefx].condition.length = 5000;
for (i = 0; i < SDL_HapticNumAxes(haptic); i++) {
efx[nefx].condition.right_sat[i] = 0xFFFF;
efx[nefx].condition.left_sat[i] = 0xFFFF;
efx[nefx].condition.right_coeff[i] = 0x2000;
efx[nefx].condition.left_coeff[i] = 0x2000;
efx[nefx].condition.deadband[i] = 0x1000; /* 1/16th of axis-range around the center is 'dead'. */
}
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* The hot friction effect. */
if (supported & SDL_HAPTIC_FRICTION) {
SDL_Log(" effect %d: Condition Friction\n", nefx);
efx[nefx].type = SDL_HAPTIC_FRICTION;
efx[nefx].condition.length = 5000;
for (i = 0; i < SDL_HapticNumAxes(haptic); i++) {
efx[nefx].condition.right_sat[i] = 0xFFFF;
efx[nefx].condition.left_sat[i] = 0xFFFF;
efx[nefx].condition.right_coeff[i] = 0x2000;
efx[nefx].condition.left_coeff[i] = 0x2000;
}
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* Now we'll try a ramp effect */
if (supported & SDL_HAPTIC_RAMP) {
SDL_Log(" effect %d: Ramp\n", nefx);
efx[nefx].type = SDL_HAPTIC_RAMP;
efx[nefx].ramp.direction.type = SDL_HAPTIC_CARTESIAN;
efx[nefx].ramp.direction.dir[0] = 1; /* Force comes from */
efx[nefx].ramp.direction.dir[1] = -1; /* the north-east. */
efx[nefx].ramp.length = 5000;
efx[nefx].ramp.start = 0x4000;
efx[nefx].ramp.end = -0x4000;
efx[nefx].ramp.attack_length = 1000;
efx[nefx].ramp.fade_length = 1000;
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
/* Finally we'll try a left/right effect. */
if (supported & SDL_HAPTIC_LEFTRIGHT) {
SDL_Log(" effect %d: Left/Right\n", nefx);
efx[nefx].type = SDL_HAPTIC_LEFTRIGHT;
efx[nefx].leftright.length = 5000;
efx[nefx].leftright.large_magnitude = 0x3000;
efx[nefx].leftright.small_magnitude = 0xFFFF;
id[nefx] = SDL_HapticNewEffect(haptic, &efx[nefx]);
if (id[nefx] < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "UPLOADING EFFECT ERROR: %s\n", SDL_GetError());
abort_execution();
}
nefx++;
}
SDL_Log
("\nNow playing effects for 5 seconds each with 1 second delay between\n");
for (i = 0; i < nefx; i++) {
SDL_Log(" Playing effect %d\n", i);
SDL_HapticRunEffect(haptic, id[i], 1);
SDL_Delay(6000); /* Effects only have length 5000 */
}
/* Quit */
if (haptic != NULL)
SDL_HapticClose(haptic);
SDL_Quit();
return 0;
}
/*
* Cleans up a bit.
*/
static void
abort_execution(void)
{
SDL_Log("\nAborting program execution.\n");
SDL_HapticClose(haptic);
SDL_Quit();
exit(1);
}
/*
* Displays information about the haptic device.
*/
static void
HapticPrintSupported(SDL_Haptic * haptic)
{
unsigned int supported;
supported = SDL_HapticQuery(haptic);
SDL_Log(" Supported effects [%d effects, %d playing]:\n",
SDL_HapticNumEffects(haptic), SDL_HapticNumEffectsPlaying(haptic));
if (supported & SDL_HAPTIC_CONSTANT)
SDL_Log(" constant\n");
if (supported & SDL_HAPTIC_SINE)
SDL_Log(" sine\n");
/* !!! FIXME: put this back when we have more bits in 2.1 */
/* if (supported & SDL_HAPTIC_SQUARE)
SDL_Log(" square\n"); */
if (supported & SDL_HAPTIC_TRIANGLE)
SDL_Log(" triangle\n");
if (supported & SDL_HAPTIC_SAWTOOTHUP)
SDL_Log(" sawtoothup\n");
if (supported & SDL_HAPTIC_SAWTOOTHDOWN)
SDL_Log(" sawtoothdown\n");
if (supported & SDL_HAPTIC_RAMP)
SDL_Log(" ramp\n");
if (supported & SDL_HAPTIC_FRICTION)
SDL_Log(" friction\n");
if (supported & SDL_HAPTIC_SPRING)
SDL_Log(" spring\n");
if (supported & SDL_HAPTIC_DAMPER)
SDL_Log(" damper\n");
if (supported & SDL_HAPTIC_INERTIA)
SDL_Log(" inertia\n");
if (supported & SDL_HAPTIC_CUSTOM)
SDL_Log(" custom\n");
if (supported & SDL_HAPTIC_LEFTRIGHT)
SDL_Log(" left/right\n");
SDL_Log(" Supported capabilities:\n");
if (supported & SDL_HAPTIC_GAIN)
SDL_Log(" gain\n");
if (supported & SDL_HAPTIC_AUTOCENTER)
SDL_Log(" autocenter\n");
if (supported & SDL_HAPTIC_STATUS)
SDL_Log(" status\n");
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Haptic support.\n");
return 1;
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testhaptic.c | C | apache-2.0 | 13,827 |
#include <stdio.h>
#include "SDL.h"
/* !!! FIXME: rewrite this to be wired in to test framework. */
#define RESIZE_BORDER 20
const SDL_Rect drag_areas[] = {
{ 20, 20, 100, 100 },
{ 200, 70, 100, 100 },
{ 400, 90, 100, 100 }
};
static const SDL_Rect *areas = drag_areas;
static int numareas = SDL_arraysize(drag_areas);
static SDL_HitTestResult SDLCALL
hitTest(SDL_Window *window, const SDL_Point *pt, void *data)
{
int i;
int w, h;
for (i = 0; i < numareas; i++) {
if (SDL_PointInRect(pt, &areas[i])) {
SDL_Log("HIT-TEST: DRAGGABLE\n");
return SDL_HITTEST_DRAGGABLE;
}
}
SDL_GetWindowSize(window, &w, &h);
#define REPORT_RESIZE_HIT(name) { \
SDL_Log("HIT-TEST: RESIZE_" #name "\n"); \
return SDL_HITTEST_RESIZE_##name; \
}
if (pt->x < RESIZE_BORDER && pt->y < RESIZE_BORDER) {
REPORT_RESIZE_HIT(TOPLEFT);
} else if (pt->x > RESIZE_BORDER && pt->x < w - RESIZE_BORDER && pt->y < RESIZE_BORDER) {
REPORT_RESIZE_HIT(TOP);
} else if (pt->x > w - RESIZE_BORDER && pt->y < RESIZE_BORDER) {
REPORT_RESIZE_HIT(TOPRIGHT);
} else if (pt->x > w - RESIZE_BORDER && pt->y > RESIZE_BORDER && pt->y < h - RESIZE_BORDER) {
REPORT_RESIZE_HIT(RIGHT);
} else if (pt->x > w - RESIZE_BORDER && pt->y > h - RESIZE_BORDER) {
REPORT_RESIZE_HIT(BOTTOMRIGHT);
} else if (pt->x < w - RESIZE_BORDER && pt->x > RESIZE_BORDER && pt->y > h - RESIZE_BORDER) {
REPORT_RESIZE_HIT(BOTTOM);
} else if (pt->x < RESIZE_BORDER && pt->y > h - RESIZE_BORDER) {
REPORT_RESIZE_HIT(BOTTOMLEFT);
} else if (pt->x < RESIZE_BORDER && pt->y < h - RESIZE_BORDER && pt->y > RESIZE_BORDER) {
REPORT_RESIZE_HIT(LEFT);
}
SDL_Log("HIT-TEST: NORMAL\n");
return SDL_HITTEST_NORMAL;
}
int main(int argc, char **argv)
{
int done = 0;
SDL_Window *window;
SDL_Renderer *renderer;
/* !!! FIXME: check for errors. */
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("Drag the red boxes", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE);
renderer = SDL_CreateRenderer(window, -1, 0);
if (SDL_SetWindowHitTest(window, hitTest, NULL) == -1) {
SDL_Log("Enabling hit-testing failed!\n");
SDL_Quit();
return 1;
}
while (!done)
{
SDL_Event e;
int nothing_to_do = 1;
SDL_SetRenderDrawColor(renderer, 0, 0, 127, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRects(renderer, areas, SDL_arraysize(drag_areas));
SDL_RenderPresent(renderer);
while (SDL_PollEvent(&e)) {
nothing_to_do = 0;
switch (e.type)
{
case SDL_MOUSEBUTTONDOWN:
SDL_Log("button down!\n");
break;
case SDL_MOUSEBUTTONUP:
SDL_Log("button up!\n");
break;
case SDL_WINDOWEVENT:
if (e.window.event == SDL_WINDOWEVENT_MOVED) {
SDL_Log("Window event moved to (%d, %d)!\n", (int) e.window.data1, (int) e.window.data2);
}
break;
case SDL_KEYDOWN:
if (e.key.keysym.sym == SDLK_ESCAPE) {
done = 1;
} else if (e.key.keysym.sym == SDLK_x) {
if (!areas) {
areas = drag_areas;
numareas = SDL_arraysize(drag_areas);
} else {
areas = NULL;
numareas = 0;
}
}
break;
case SDL_QUIT:
done = 1;
break;
}
}
if (nothing_to_do) {
SDL_Delay(50);
}
}
SDL_Quit();
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testhittesting.c | C | apache-2.0 | 4,082 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program to test the SDL joystick hotplugging */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
#if !defined SDL_JOYSTICK_DISABLED && !defined SDL_HAPTIC_DISABLED
int
main(int argc, char *argv[])
{
SDL_Joystick *joystick = NULL;
SDL_Haptic *haptic = NULL;
SDL_JoystickID instance = -1;
SDL_bool keepGoing = SDL_TRUE;
int i;
SDL_bool enable_haptic = SDL_TRUE;
Uint32 init_subsystems = SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
for (i = 1; i < argc; ++i) {
if (SDL_strcasecmp(argv[i], "--nohaptic") == 0) {
enable_haptic = SDL_FALSE;
}
}
if(enable_haptic) {
init_subsystems |= SDL_INIT_HAPTIC;
}
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
/* Initialize SDL (Note: video is required to start event loop) */
if (SDL_Init(init_subsystems) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
exit(1);
}
/*
//SDL_CreateWindow("Dummy", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 128, 128, 0);
*/
SDL_Log("There are %d joysticks at startup\n", SDL_NumJoysticks());
if (enable_haptic)
SDL_Log("There are %d haptic devices at startup\n", SDL_NumHaptics());
while(keepGoing)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
keepGoing = SDL_FALSE;
break;
case SDL_JOYDEVICEADDED:
if (joystick != NULL)
{
SDL_Log("Only one joystick supported by this test\n");
}
else
{
joystick = SDL_JoystickOpen(event.jdevice.which);
instance = SDL_JoystickInstanceID(joystick);
SDL_Log("Joy Added : %d : %s\n", event.jdevice.which, SDL_JoystickName(joystick));
if (enable_haptic)
{
if (SDL_JoystickIsHaptic(joystick))
{
haptic = SDL_HapticOpenFromJoystick(joystick);
if (haptic)
{
SDL_Log("Joy Haptic Opened\n");
if (SDL_HapticRumbleInit( haptic ) != 0)
{
SDL_Log("Could not init Rumble!: %s\n", SDL_GetError());
SDL_HapticClose(haptic);
haptic = NULL;
}
} else {
SDL_Log("Joy haptic open FAILED!: %s\n", SDL_GetError());
}
}
else
{
SDL_Log("No haptic found\n");
}
}
}
break;
case SDL_JOYDEVICEREMOVED:
if (instance == event.jdevice.which)
{
SDL_Log("Joy Removed: %d\n", event.jdevice.which);
instance = -1;
if(enable_haptic && haptic)
{
SDL_HapticClose(haptic);
haptic = NULL;
}
SDL_JoystickClose(joystick);
joystick = NULL;
} else {
SDL_Log("Unknown joystick diconnected\n");
}
break;
case SDL_JOYAXISMOTION:
/*
// SDL_Log("Axis Move: %d\n", event.jaxis.axis);
*/
if (enable_haptic)
SDL_HapticRumblePlay(haptic, 0.25, 250);
break;
case SDL_JOYBUTTONDOWN:
SDL_Log("Button Press: %d\n", event.jbutton.button);
if(enable_haptic && haptic)
{
SDL_HapticRumblePlay(haptic, 0.25, 250);
}
if (event.jbutton.button == 0) {
SDL_Log("Exiting due to button press of button 0\n");
keepGoing = SDL_FALSE;
}
break;
case SDL_JOYBUTTONUP:
SDL_Log("Button Release: %d\n", event.jbutton.button);
break;
}
}
}
SDL_Quit();
return 0;
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick and haptic support.\n");
return 1;
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testhotplug.c | C | apache-2.0 | 5,564 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdio.h>
#include "SDL.h"
static size_t
widelen(char *data)
{
size_t len = 0;
Uint32 *p = (Uint32 *) data;
while (*p++) {
++len;
}
return len;
}
int
main(int argc, char *argv[])
{
const char *formats[] = {
"UTF8",
"UTF-8",
"UTF16BE",
"UTF-16BE",
"UTF16LE",
"UTF-16LE",
"UTF32BE",
"UTF-32BE",
"UTF32LE",
"UTF-32LE",
"UCS4",
"UCS-4",
};
char buffer[BUFSIZ];
char *ucs4;
char *test[2];
int i;
FILE *file;
int errors = 0;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (!argv[1]) {
argv[1] = "utf8.txt";
}
file = fopen(argv[1], "rb");
if (!file) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to open %s\n", argv[1]);
return (1);
}
while (fgets(buffer, sizeof(buffer), file)) {
/* Convert to UCS-4 */
size_t len;
ucs4 =
SDL_iconv_string("UCS-4", "UTF-8", buffer,
SDL_strlen(buffer) + 1);
len = (widelen(ucs4) + 1) * 4;
for (i = 0; i < SDL_arraysize(formats); ++i) {
test[0] = SDL_iconv_string(formats[i], "UCS-4", ucs4, len);
test[1] = SDL_iconv_string("UCS-4", formats[i], test[0], len);
if (!test[1] || SDL_memcmp(test[1], ucs4, len) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "FAIL: %s\n", formats[i]);
++errors;
}
SDL_free(test[0]);
SDL_free(test[1]);
}
test[0] = SDL_iconv_string("UTF-8", "UCS-4", ucs4, len);
SDL_free(ucs4);
fputs(test[0], stdout);
SDL_free(test[0]);
}
fclose(file);
return (errors ? errors + 1 : 0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testiconv.c | C | apache-2.0 | 2,278 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* A simple program to test the Input Method support in the SDL library (2.0+)
If you build without SDL_ttf, you can use the GNU Unifont hex file instead.
Download at http://unifoundry.com/unifont.html */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "SDL.h"
#ifdef HAVE_SDL_TTF
#include "SDL_ttf.h"
#endif
#include "SDL_test_common.h"
#define DEFAULT_PTSIZE 30
#ifdef HAVE_SDL_TTF
#ifdef __MACOSX__
#define DEFAULT_FONT "/System/Library/Fonts/华文细黑.ttf"
#elif __WIN32__
/* Some japanese font present on at least Windows 8.1. */
#define DEFAULT_FONT "C:\\Windows\\Fonts\\yugothic.ttf"
#else
#define DEFAULT_FONT "NoDefaultFont.ttf"
#endif
#else
#define DEFAULT_FONT "unifont-9.0.02.hex"
#endif
#define MAX_TEXT_LENGTH 256
static SDLTest_CommonState *state;
static SDL_Rect textRect, markedRect;
static SDL_Color lineColor = {0,0,0,255};
static SDL_Color backColor = {255,255,255,255};
static SDL_Color textColor = {0,0,0,255};
static char text[MAX_TEXT_LENGTH], markedText[SDL_TEXTEDITINGEVENT_TEXT_SIZE];
static int cursor = 0;
#ifdef HAVE_SDL_TTF
static TTF_Font *font;
#else
#define UNIFONT_MAX_CODEPOINT 0x1ffff
#define UNIFONT_NUM_GLYPHS 0x20000
/* Using 512x512 textures that are supported everywhere. */
#define UNIFONT_TEXTURE_WIDTH 512
#define UNIFONT_GLYPHS_IN_ROW (UNIFONT_TEXTURE_WIDTH / 16)
#define UNIFONT_GLYPHS_IN_TEXTURE (UNIFONT_GLYPHS_IN_ROW * UNIFONT_GLYPHS_IN_ROW)
#define UNIFONT_NUM_TEXTURES ((UNIFONT_NUM_GLYPHS + UNIFONT_GLYPHS_IN_TEXTURE - 1) / UNIFONT_GLYPHS_IN_TEXTURE)
#define UNIFONT_TEXTURE_SIZE (UNIFONT_TEXTURE_WIDTH * UNIFONT_TEXTURE_WIDTH * 4)
#define UNIFONT_TEXTURE_PITCH (UNIFONT_TEXTURE_WIDTH * 4)
#define UNIFONT_DRAW_SCALE 2
struct UnifontGlyph {
Uint8 width;
Uint8 data[32];
} *unifontGlyph;
static SDL_Texture **unifontTexture;
static Uint8 unifontTextureLoaded[UNIFONT_NUM_TEXTURES] = {0};
/* Unifont loading code start */
static Uint8 dehex(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
else if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return 255;
}
static Uint8 dehex2(char c1, char c2)
{
return (dehex(c1) << 4) | dehex(c2);
}
static Uint8 validate_hex(const char *cp, size_t len, Uint32 *np)
{
Uint32 n = 0;
for (; len > 0; cp++, len--)
{
Uint8 c = dehex(*cp);
if (c == 255)
return 0;
n = (n << 4) | c;
}
if (np != NULL)
*np = n;
return 1;
}
static int unifont_init(const char *fontname)
{
Uint8 hexBuffer[65];
Uint32 numGlyphs = 0;
int lineNumber = 1;
size_t bytesRead;
SDL_RWops *hexFile;
const size_t unifontGlyphSize = UNIFONT_NUM_GLYPHS * sizeof(struct UnifontGlyph);
const size_t unifontTextureSize = UNIFONT_NUM_TEXTURES * state->num_windows * sizeof(void *);
/* Allocate memory for the glyph data so the file can be closed after initialization. */
unifontGlyph = (struct UnifontGlyph *)SDL_malloc(unifontGlyphSize);
if (unifontGlyph == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d KiB for glyph data.\n", (int)(unifontGlyphSize + 1023) / 1024);
return -1;
}
SDL_memset(unifontGlyph, 0, unifontGlyphSize);
/* Allocate memory for texture pointers for all renderers. */
unifontTexture = (SDL_Texture **)SDL_malloc(unifontTextureSize);
if (unifontTexture == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d KiB for texture pointer data.\n", (int)(unifontTextureSize + 1023) / 1024);
return -1;
}
SDL_memset(unifontTexture, 0, unifontTextureSize);
hexFile = SDL_RWFromFile(fontname, "rb");
if (hexFile == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to open font file: %s\n", fontname);
return -1;
}
/* Read all the glyph data into memory to make it accessible later when textures are created. */
do {
int i, codepointHexSize;
size_t bytesOverread;
Uint8 glyphWidth;
Uint32 codepoint;
bytesRead = SDL_RWread(hexFile, hexBuffer, 1, 9);
if (numGlyphs > 0 && bytesRead == 0)
break; /* EOF */
if ((numGlyphs == 0 && bytesRead == 0) || (numGlyphs > 0 && bytesRead < 9))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
return -1;
}
/* Looking for the colon that separates the codepoint and glyph data at position 2, 4, 6 and 8. */
if (hexBuffer[2] == ':')
codepointHexSize = 2;
else if (hexBuffer[4] == ':')
codepointHexSize = 4;
else if (hexBuffer[6] == ':')
codepointHexSize = 6;
else if (hexBuffer[8] == ':')
codepointHexSize = 8;
else
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Could not find codepoint and glyph data separator symbol in hex file on line %d.\n", lineNumber);
return -1;
}
if (!validate_hex((const char *)hexBuffer, codepointHexSize, &codepoint))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Malformed hexadecimal number in hex file on line %d.\n", lineNumber);
return -1;
}
if (codepoint > UNIFONT_MAX_CODEPOINT)
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "unifont: Codepoint on line %d exceeded limit of 0x%x.\n", lineNumber, UNIFONT_MAX_CODEPOINT);
/* If there was glyph data read in the last file read, move it to the front of the buffer. */
bytesOverread = 8 - codepointHexSize;
if (codepointHexSize < 8)
SDL_memmove(hexBuffer, hexBuffer + codepointHexSize + 1, bytesOverread);
bytesRead = SDL_RWread(hexFile, hexBuffer + bytesOverread, 1, 33 - bytesOverread);
if (bytesRead < (33 - bytesOverread))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
return -1;
}
if (hexBuffer[32] == '\n')
glyphWidth = 8;
else
{
glyphWidth = 16;
bytesRead = SDL_RWread(hexFile, hexBuffer + 33, 1, 32);
if (bytesRead < 32)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Unexpected end of hex file.\n");
return -1;
}
}
if (!validate_hex((const char *)hexBuffer, glyphWidth * 4, NULL))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Malformed hexadecimal glyph data in hex file on line %d.\n", lineNumber);
return -1;
}
if (codepoint <= UNIFONT_MAX_CODEPOINT)
{
if (unifontGlyph[codepoint].width > 0)
SDL_LogWarn(SDL_LOG_CATEGORY_APPLICATION, "unifont: Ignoring duplicate codepoint 0x%08x in hex file on line %d.\n", codepoint, lineNumber);
else
{
unifontGlyph[codepoint].width = glyphWidth;
/* Pack the hex data into a more compact form. */
for (i = 0; i < glyphWidth * 2; i++)
unifontGlyph[codepoint].data[i] = dehex2(hexBuffer[i * 2], hexBuffer[i * 2 + 1]);
numGlyphs++;
}
}
lineNumber++;
} while (bytesRead > 0);
SDL_RWclose(hexFile);
SDL_Log("unifont: Loaded %u glyphs.\n", numGlyphs);
return 0;
}
static void unifont_make_rgba(Uint8 *src, Uint8 *dst, Uint8 width)
{
int i, j;
Uint8 *row = dst;
for (i = 0; i < width * 2; i++)
{
Uint8 data = src[i];
for (j = 0; j < 8; j++)
{
if (data & 0x80)
{
row[0] = textColor.r;
row[1] = textColor.g;
row[2] = textColor.b;
row[3] = textColor.a;
}
else
{
row[0] = 0;
row[1] = 0;
row[2] = 0;
row[3] = 0;
}
data <<= 1;
row += 4;
}
if (width == 8 || (width == 16 && i % 2 == 1))
{
dst += UNIFONT_TEXTURE_PITCH;
row = dst;
}
}
}
static int unifont_load_texture(Uint32 textureID)
{
int i;
Uint8 * textureRGBA;
if (textureID >= UNIFONT_NUM_TEXTURES)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Tried to load out of range texture %u.\n", textureID);
return -1;
}
textureRGBA = (Uint8 *)SDL_malloc(UNIFONT_TEXTURE_SIZE);
if (textureRGBA == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to allocate %d MiB for a texture.\n", UNIFONT_TEXTURE_SIZE / 1024 / 1024);
return -1;
}
SDL_memset(textureRGBA, 0, UNIFONT_TEXTURE_SIZE);
/* Copy the glyphs into memory in RGBA format. */
for (i = 0; i < UNIFONT_GLYPHS_IN_TEXTURE; i++)
{
Uint32 codepoint = UNIFONT_GLYPHS_IN_TEXTURE * textureID + i;
if (unifontGlyph[codepoint].width > 0)
{
const Uint32 cInTex = codepoint % UNIFONT_GLYPHS_IN_TEXTURE;
const size_t offset = (cInTex / UNIFONT_GLYPHS_IN_ROW) * UNIFONT_TEXTURE_PITCH * 16 + (cInTex % UNIFONT_GLYPHS_IN_ROW) * 16 * 4;
unifont_make_rgba(unifontGlyph[codepoint].data, textureRGBA + offset, unifontGlyph[codepoint].width);
}
}
/* Create textures and upload the RGBA data from above. */
for (i = 0; i < state->num_windows; ++i)
{
SDL_Renderer *renderer = state->renderers[i];
SDL_Texture *tex = unifontTexture[UNIFONT_NUM_TEXTURES * i + textureID];
if (state->windows[i] == NULL || renderer == NULL || tex != NULL)
continue;
tex = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, UNIFONT_TEXTURE_WIDTH, UNIFONT_TEXTURE_WIDTH);
if (tex == NULL)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "unifont: Failed to create texture %u for renderer %d.\n", textureID, i);
return -1;
}
unifontTexture[UNIFONT_NUM_TEXTURES * i + textureID] = tex;
SDL_SetTextureBlendMode(tex, SDL_BLENDMODE_BLEND);
if (SDL_UpdateTexture(tex, NULL, textureRGBA, UNIFONT_TEXTURE_PITCH) != 0)
{
SDL_Log("unifont error: Failed to update texture %u data for renderer %d.\n", textureID, i);
}
}
SDL_free(textureRGBA);
unifontTextureLoaded[textureID] = 1;
return 0;
}
static Sint32 unifont_draw_glyph(Uint32 codepoint, int rendererID, SDL_Rect *dstrect)
{
SDL_Texture *texture;
const Uint32 textureID = codepoint / UNIFONT_GLYPHS_IN_TEXTURE;
SDL_Rect srcrect;
srcrect.w = srcrect.h = 16;
if (codepoint > UNIFONT_MAX_CODEPOINT) {
return 0;
}
if (!unifontTextureLoaded[textureID]) {
if (unifont_load_texture(textureID) < 0) {
return 0;
}
}
texture = unifontTexture[UNIFONT_NUM_TEXTURES * rendererID + textureID];
if (texture != NULL)
{
const Uint32 cInTex = codepoint % UNIFONT_GLYPHS_IN_TEXTURE;
srcrect.x = cInTex % UNIFONT_GLYPHS_IN_ROW * 16;
srcrect.y = cInTex / UNIFONT_GLYPHS_IN_ROW * 16;
SDL_RenderCopy(state->renderers[rendererID], texture, &srcrect, dstrect);
}
return unifontGlyph[codepoint].width;
}
static void unifont_cleanup()
{
int i, j;
for (i = 0; i < state->num_windows; ++i)
{
SDL_Renderer *renderer = state->renderers[i];
if (state->windows[i] == NULL || renderer == NULL)
continue;
for (j = 0; j < UNIFONT_NUM_TEXTURES; j++)
{
SDL_Texture *tex = unifontTexture[UNIFONT_NUM_TEXTURES * i + j];
if (tex != NULL)
SDL_DestroyTexture(tex);
}
}
for (j = 0; j < UNIFONT_NUM_TEXTURES; j++)
unifontTextureLoaded[j] = 0;
SDL_free(unifontTexture);
SDL_free(unifontGlyph);
}
/* Unifont code end */
#endif
size_t utf8_length(unsigned char c)
{
c = (unsigned char)(0xff & c);
if (c < 0x80)
return 1;
else if ((c >> 5) ==0x6)
return 2;
else if ((c >> 4) == 0xe)
return 3;
else if ((c >> 3) == 0x1e)
return 4;
else
return 0;
}
char *utf8_next(char *p)
{
size_t len = utf8_length(*p);
size_t i = 0;
if (!len)
return 0;
for (; i < len; ++i)
{
++p;
if (!*p)
return 0;
}
return p;
}
char *utf8_advance(char *p, size_t distance)
{
size_t i = 0;
for (; i < distance && p; ++i)
{
p = utf8_next(p);
}
return p;
}
Uint32 utf8_decode(char *p, size_t len)
{
Uint32 codepoint = 0;
size_t i = 0;
if (!len)
return 0;
for (; i < len; ++i)
{
if (i == 0)
codepoint = (0xff >> len) & *p;
else
{
codepoint <<= 6;
codepoint |= 0x3f & *p;
}
if (!*p)
return 0;
p++;
}
return codepoint;
}
void usage()
{
SDL_Log("usage: testime [--font fontfile]\n");
}
void InitInput()
{
/* Prepare a rect for text input */
textRect.x = textRect.y = 100;
textRect.w = DEFAULT_WINDOW_WIDTH - 2 * textRect.x;
textRect.h = 50;
text[0] = 0;
markedRect = textRect;
markedText[0] = 0;
SDL_StartTextInput();
}
void CleanupVideo()
{
SDL_StopTextInput();
#ifdef HAVE_SDL_TTF
TTF_CloseFont(font);
TTF_Quit();
#else
unifont_cleanup();
#endif
}
void _Redraw(int rendererID)
{
SDL_Renderer * renderer = state->renderers[rendererID];
SDL_Rect drawnTextRect, cursorRect, underlineRect;
drawnTextRect = textRect;
drawnTextRect.w = 0;
SDL_SetRenderDrawColor(renderer, backColor.r, backColor.g, backColor.b, backColor.a);
SDL_RenderFillRect(renderer,&textRect);
if (*text)
{
#ifdef HAVE_SDL_TTF
SDL_Surface *textSur = TTF_RenderUTF8_Blended(font, text, textColor);
SDL_Texture *texture;
/* Vertically center text */
drawnTextRect.y = textRect.y + (textRect.h - textSur->h) / 2;
drawnTextRect.w = textSur->w;
drawnTextRect.h = textSur->h;
texture = SDL_CreateTextureFromSurface(renderer,textSur);
SDL_FreeSurface(textSur);
SDL_RenderCopy(renderer,texture,NULL,&drawnTextRect);
SDL_DestroyTexture(texture);
#else
char *utext = text;
Uint32 codepoint;
size_t len;
SDL_Rect dstrect;
dstrect.x = textRect.x;
dstrect.y = textRect.y + (textRect.h - 16 * UNIFONT_DRAW_SCALE) / 2;
dstrect.w = 16 * UNIFONT_DRAW_SCALE;
dstrect.h = 16 * UNIFONT_DRAW_SCALE;
drawnTextRect.y = dstrect.y;
drawnTextRect.h = dstrect.h;
while ((codepoint = utf8_decode(utext, len = utf8_length(*utext))))
{
Sint32 advance = unifont_draw_glyph(codepoint, rendererID, &dstrect) * UNIFONT_DRAW_SCALE;
dstrect.x += advance;
drawnTextRect.w += advance;
utext += len;
}
#endif
}
markedRect.x = textRect.x + drawnTextRect.w;
markedRect.w = textRect.w - drawnTextRect.w;
if (markedRect.w < 0)
{
/* Stop text input because we cannot hold any more characters */
SDL_StopTextInput();
return;
}
else
{
SDL_StartTextInput();
}
cursorRect = drawnTextRect;
cursorRect.x += cursorRect.w;
cursorRect.w = 2;
cursorRect.h = drawnTextRect.h;
drawnTextRect.x += drawnTextRect.w;
drawnTextRect.w = 0;
SDL_SetRenderDrawColor(renderer, backColor.r, backColor.g, backColor.b, backColor.a);
SDL_RenderFillRect(renderer,&markedRect);
if (markedText[0])
{
#ifdef HAVE_SDL_TTF
SDL_Surface *textSur;
SDL_Texture *texture;
if (cursor)
{
char *p = utf8_advance(markedText, cursor);
char c = 0;
if (!p)
p = &markedText[SDL_strlen(markedText)];
c = *p;
*p = 0;
TTF_SizeUTF8(font, markedText, &drawnTextRect.w, NULL);
cursorRect.x += drawnTextRect.w;
*p = c;
}
textSur = TTF_RenderUTF8_Blended(font, markedText, textColor);
/* Vertically center text */
drawnTextRect.y = textRect.y + (textRect.h - textSur->h) / 2;
drawnTextRect.w = textSur->w;
drawnTextRect.h = textSur->h;
texture = SDL_CreateTextureFromSurface(renderer,textSur);
SDL_FreeSurface(textSur);
SDL_RenderCopy(renderer,texture,NULL,&drawnTextRect);
SDL_DestroyTexture(texture);
#else
int i = 0;
char *utext = markedText;
Uint32 codepoint;
size_t len;
SDL_Rect dstrect;
dstrect.x = drawnTextRect.x;
dstrect.y = textRect.y + (textRect.h - 16 * UNIFONT_DRAW_SCALE) / 2;
dstrect.w = 16 * UNIFONT_DRAW_SCALE;
dstrect.h = 16 * UNIFONT_DRAW_SCALE;
drawnTextRect.y = dstrect.y;
drawnTextRect.h = dstrect.h;
while ((codepoint = utf8_decode(utext, len = utf8_length(*utext))))
{
Sint32 advance = unifont_draw_glyph(codepoint, rendererID, &dstrect) * UNIFONT_DRAW_SCALE;
dstrect.x += advance;
drawnTextRect.w += advance;
if (i < cursor)
cursorRect.x += advance;
i++;
utext += len;
}
#endif
if (cursor > 0)
{
cursorRect.y = drawnTextRect.y;
cursorRect.h = drawnTextRect.h;
}
underlineRect = markedRect;
underlineRect.y = drawnTextRect.y + drawnTextRect.h - 2;
underlineRect.h = 2;
underlineRect.w = drawnTextRect.w;
SDL_SetRenderDrawColor(renderer, lineColor.r, lineColor.g, lineColor.b, lineColor.a);
SDL_RenderFillRect(renderer, &underlineRect);
}
SDL_SetRenderDrawColor(renderer, lineColor.r, lineColor.g, lineColor.b, lineColor.a);
SDL_RenderFillRect(renderer,&cursorRect);
SDL_SetTextInputRect(&markedRect);
}
void Redraw()
{
int i;
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
if (state->windows[i] == NULL)
continue;
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0);
SDL_RenderClear(renderer);
/* Sending in the window id to let the font renderers know which one we're working with. */
_Redraw(i);
SDL_RenderPresent(renderer);
}
}
int main(int argc, char *argv[])
{
int i, done;
SDL_Event event;
const char *fontname = DEFAULT_FONT;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;i++) {
SDLTest_CommonArg(state, i);
}
for (argc--, argv++; argc > 0; argc--, argv++)
{
if (strcmp(argv[0], "--help") == 0) {
usage();
return 0;
}
else if (strcmp(argv[0], "--font") == 0)
{
argc--;
argv++;
if (argc > 0)
fontname = argv[0];
else {
usage();
return 0;
}
}
}
if (!SDLTest_CommonInit(state)) {
return 2;
}
#ifdef HAVE_SDL_TTF
/* Initialize fonts */
TTF_Init();
font = TTF_OpenFont(fontname, DEFAULT_PTSIZE);
if (! font)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to find font: %s\n", TTF_GetError());
return -1;
}
#else
if (unifont_init(fontname) < 0) {
return -1;
}
#endif
SDL_Log("Using font: %s\n", fontname);
InitInput();
/* Create the windows and initialize the renderers */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
Redraw();
/* Main render loop */
done = 0;
while (!done) {
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
switch(event.type) {
case SDL_KEYDOWN: {
switch (event.key.keysym.sym)
{
case SDLK_RETURN:
text[0]=0x00;
Redraw();
break;
case SDLK_BACKSPACE:
/* Only delete text if not in editing mode. */
if (!markedText[0])
{
size_t textlen = SDL_strlen(text);
do {
if (textlen==0)
{
break;
}
if ((text[textlen-1] & 0x80) == 0x00)
{
/* One byte */
text[textlen-1]=0x00;
break;
}
if ((text[textlen-1] & 0xC0) == 0x80)
{
/* Byte from the multibyte sequence */
text[textlen-1]=0x00;
textlen--;
}
if ((text[textlen-1] & 0xC0) == 0xC0)
{
/* First byte of multibyte sequence */
text[textlen-1]=0x00;
break;
}
} while(1);
Redraw();
}
break;
}
if (done)
{
break;
}
SDL_Log("Keyboard: scancode 0x%08X = %s, keycode 0x%08X = %s\n",
event.key.keysym.scancode,
SDL_GetScancodeName(event.key.keysym.scancode),
event.key.keysym.sym, SDL_GetKeyName(event.key.keysym.sym));
break;
case SDL_TEXTINPUT:
if (event.text.text[0] == '\0' || event.text.text[0] == '\n' ||
markedRect.w < 0)
break;
SDL_Log("Keyboard: text input \"%s\"\n", event.text.text);
if (SDL_strlen(text) + SDL_strlen(event.text.text) < sizeof(text))
SDL_strlcat(text, event.text.text, sizeof(text));
SDL_Log("text inputed: %s\n", text);
/* After text inputed, we can clear up markedText because it */
/* is committed */
markedText[0] = 0;
Redraw();
break;
case SDL_TEXTEDITING:
SDL_Log("text editing \"%s\", selected range (%d, %d)\n",
event.edit.text, event.edit.start, event.edit.length);
SDL_strlcpy(markedText, event.edit.text, SDL_TEXTEDITINGEVENT_TEXT_SIZE);
cursor = event.edit.start;
Redraw();
break;
}
break;
}
}
}
CleanupVideo();
SDLTest_CommonQuit(state);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testime.c | C | apache-2.0 | 24,655 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: draw as many random objects on the screen as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
#define SWAP(typ,a,b) do{typ t=a;a=b;b=t;}while(0)
#define NUM_OBJECTS 100
static SDLTest_CommonState *state;
static int num_objects;
static SDL_bool cycle_color;
static SDL_bool cycle_alpha;
static int cycle_direction = 1;
static int current_alpha = 255;
static int current_color = 255;
static SDL_BlendMode blendMode = SDL_BLENDMODE_NONE;
int mouse_begin_x = -1, mouse_begin_y = -1;
int done;
void
DrawPoints(SDL_Renderer * renderer)
{
int i;
int x, y;
SDL_Rect viewport;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
for (i = 0; i < num_objects * 4; ++i) {
/* Cycle the color and alpha, if desired */
if (cycle_color) {
current_color += cycle_direction;
if (current_color < 0) {
current_color = 0;
cycle_direction = -cycle_direction;
}
if (current_color > 255) {
current_color = 255;
cycle_direction = -cycle_direction;
}
}
if (cycle_alpha) {
current_alpha += cycle_direction;
if (current_alpha < 0) {
current_alpha = 0;
cycle_direction = -cycle_direction;
}
if (current_alpha > 255) {
current_alpha = 255;
cycle_direction = -cycle_direction;
}
}
SDL_SetRenderDrawColor(renderer, 255, (Uint8) current_color,
(Uint8) current_color, (Uint8) current_alpha);
x = rand() % viewport.w;
y = rand() % viewport.h;
SDL_RenderDrawPoint(renderer, x, y);
}
}
#define MAX_LINES 16
int num_lines = 0;
SDL_Rect lines[MAX_LINES];
static int
add_line(int x1, int y1, int x2, int y2)
{
if (num_lines >= MAX_LINES)
return 0;
if ((x1 == x2) && (y1 == y2))
return 0;
SDL_Log("adding line (%d, %d), (%d, %d)\n", x1, y1, x2, y2);
lines[num_lines].x = x1;
lines[num_lines].y = y1;
lines[num_lines].w = x2;
lines[num_lines].h = y2;
return ++num_lines;
}
void
DrawLines(SDL_Renderer * renderer)
{
int i;
SDL_Rect viewport;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
for (i = 0; i < num_lines; ++i) {
if (i == -1) {
SDL_RenderDrawLine(renderer, 0, 0, viewport.w - 1, viewport.h - 1);
SDL_RenderDrawLine(renderer, 0, viewport.h - 1, viewport.w - 1, 0);
SDL_RenderDrawLine(renderer, 0, viewport.h / 2, viewport.w - 1, viewport.h / 2);
SDL_RenderDrawLine(renderer, viewport.w / 2, 0, viewport.w / 2, viewport.h - 1);
} else {
SDL_RenderDrawLine(renderer, lines[i].x, lines[i].y, lines[i].w, lines[i].h);
}
}
}
#define MAX_RECTS 16
int num_rects = 0;
SDL_Rect rects[MAX_RECTS];
static int
add_rect(int x1, int y1, int x2, int y2)
{
if (num_rects >= MAX_RECTS)
return 0;
if ((x1 == x2) || (y1 == y2))
return 0;
if (x1 > x2)
SWAP(int, x1, x2);
if (y1 > y2)
SWAP(int, y1, y2);
SDL_Log("adding rect (%d, %d), (%d, %d) [%dx%d]\n", x1, y1, x2, y2,
x2 - x1, y2 - y1);
rects[num_rects].x = x1;
rects[num_rects].y = y1;
rects[num_rects].w = x2 - x1;
rects[num_rects].h = y2 - y1;
return ++num_rects;
}
static void
DrawRects(SDL_Renderer * renderer)
{
SDL_SetRenderDrawColor(renderer, 255, 127, 0, 255);
SDL_RenderFillRects(renderer, rects, num_rects);
}
static void
DrawRectLineIntersections(SDL_Renderer * renderer)
{
int i, j;
SDL_SetRenderDrawColor(renderer, 0, 255, 55, 255);
for (i = 0; i < num_rects; i++)
for (j = 0; j < num_lines; j++) {
int x1, y1, x2, y2;
SDL_Rect r;
r = rects[i];
x1 = lines[j].x;
y1 = lines[j].y;
x2 = lines[j].w;
y2 = lines[j].h;
if (SDL_IntersectRectAndLine(&r, &x1, &y1, &x2, &y2)) {
SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
}
}
}
static void
DrawRectRectIntersections(SDL_Renderer * renderer)
{
int i, j;
SDL_SetRenderDrawColor(renderer, 255, 200, 0, 255);
for (i = 0; i < num_rects; i++)
for (j = i + 1; j < num_rects; j++) {
SDL_Rect r;
if (SDL_IntersectRect(&rects[i], &rects[j], &r)) {
SDL_RenderFillRect(renderer, &r);
}
}
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
mouse_begin_x = event.button.x;
mouse_begin_y = event.button.y;
break;
case SDL_MOUSEBUTTONUP:
if (event.button.button == 3)
add_line(mouse_begin_x, mouse_begin_y, event.button.x,
event.button.y);
if (event.button.button == 1)
add_rect(mouse_begin_x, mouse_begin_y, event.button.x,
event.button.y);
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case 'l':
if (event.key.keysym.mod & KMOD_SHIFT)
num_lines = 0;
else
add_line(rand() % 640, rand() % 480, rand() % 640,
rand() % 480);
break;
case 'r':
if (event.key.keysym.mod & KMOD_SHIFT)
num_rects = 0;
else
add_rect(rand() % 640, rand() % 480, rand() % 640,
rand() % 480);
break;
}
break;
default:
break;
}
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
if (state->windows[i] == NULL)
continue;
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
DrawRects(renderer);
DrawPoints(renderer);
DrawRectRectIntersections(renderer);
DrawLines(renderer);
DrawRectLineIntersections(renderer);
SDL_RenderPresent(renderer);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
Uint32 then, now, frames;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize parameters */
num_objects = NUM_OBJECTS;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--blend") == 0) {
if (argv[i + 1]) {
if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
blendMode = SDL_BLENDMODE_NONE;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
blendMode = SDL_BLENDMODE_BLEND;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
blendMode = SDL_BLENDMODE_ADD;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
blendMode = SDL_BLENDMODE_MOD;
consumed = 2;
}
}
} else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
cycle_color = SDL_TRUE;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
cycle_alpha = SDL_TRUE;
consumed = 1;
} else if (SDL_isdigit(*argv[i])) {
num_objects = SDL_atoi(argv[i]);
consumed = 1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--blend none|blend|add|mod]", "[--cyclecolor]", "[--cyclealpha]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
return 1;
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
return 2;
}
/* Create the windows and initialize the renderers */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawBlendMode(renderer, blendMode);
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
srand(time(NULL));
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
}
#endif
SDLTest_CommonQuit(state);
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testintersections.c | C | apache-2.0 | 10,118 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program to test the SDL joystick routines */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#ifndef SDL_JOYSTICK_DISABLED
#ifdef __IPHONEOS__
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 480
#else
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
#endif
static SDL_Window *window = NULL;
static SDL_Renderer *screen = NULL;
static SDL_Joystick *joystick = NULL;
static SDL_bool done = SDL_FALSE;
static void
PrintJoystick(SDL_Joystick *joystick)
{
const char *type;
char guid[64];
SDL_assert(SDL_JoystickFromInstanceID(SDL_JoystickInstanceID(joystick)) == joystick);
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), guid, sizeof (guid));
switch (SDL_JoystickGetType(joystick)) {
case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
type = "Game Controller";
break;
case SDL_JOYSTICK_TYPE_WHEEL:
type = "Wheel";
break;
case SDL_JOYSTICK_TYPE_ARCADE_STICK:
type = "Arcade Stick";
break;
case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
type = "Flight Stick";
break;
case SDL_JOYSTICK_TYPE_DANCE_PAD:
type = "Dance Pad";
break;
case SDL_JOYSTICK_TYPE_GUITAR:
type = "Guitar";
break;
case SDL_JOYSTICK_TYPE_DRUM_KIT:
type = "Drum Kit";
break;
case SDL_JOYSTICK_TYPE_ARCADE_PAD:
type = "Arcade Pad";
break;
case SDL_JOYSTICK_TYPE_THROTTLE:
type = "Throttle";
break;
default:
type = "Unknown";
break;
}
SDL_Log("Joystick\n");
SDL_Log(" name: %s\n", SDL_JoystickName(joystick));
SDL_Log(" type: %s\n", type);
SDL_Log(" axes: %d\n", SDL_JoystickNumAxes(joystick));
SDL_Log(" balls: %d\n", SDL_JoystickNumBalls(joystick));
SDL_Log(" hats: %d\n", SDL_JoystickNumHats(joystick));
SDL_Log(" buttons: %d\n", SDL_JoystickNumButtons(joystick));
SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick));
SDL_Log(" guid: %s\n", guid);
SDL_Log(" VID/PID: 0x%.4x/0x%.4x\n", SDL_JoystickGetVendor(joystick), SDL_JoystickGetProduct(joystick));
}
static void
DrawRect(SDL_Renderer *r, const int x, const int y, const int w, const int h)
{
const SDL_Rect area = { x, y, w, h };
SDL_RenderFillRect(r, &area);
}
void
loop(void *arg)
{
SDL_Event event;
int i;
/* blank screen, set up for drawing this frame. */
SDL_SetRenderDrawColor(screen, 0x0, 0x0, 0x0, SDL_ALPHA_OPAQUE);
SDL_RenderClear(screen);
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_JOYDEVICEADDED:
SDL_Log("Joystick device %d added.\n", (int) event.jdevice.which);
if (!joystick) {
joystick = SDL_JoystickOpen(event.jdevice.which);
if (joystick) {
PrintJoystick(joystick);
} else {
SDL_Log("Couldn't open joystick: %s\n", SDL_GetError());
}
}
break;
case SDL_JOYDEVICEREMOVED:
SDL_Log("Joystick device %d removed.\n", (int) event.jdevice.which);
if (event.jdevice.which == SDL_JoystickInstanceID(joystick)) {
SDL_JoystickClose(joystick);
joystick = SDL_JoystickOpen(0);
}
break;
case SDL_JOYAXISMOTION:
SDL_Log("Joystick %d axis %d value: %d\n",
event.jaxis.which,
event.jaxis.axis, event.jaxis.value);
break;
case SDL_JOYHATMOTION:
SDL_Log("Joystick %d hat %d value:",
event.jhat.which, event.jhat.hat);
if (event.jhat.value == SDL_HAT_CENTERED)
SDL_Log(" centered");
if (event.jhat.value & SDL_HAT_UP)
SDL_Log(" up");
if (event.jhat.value & SDL_HAT_RIGHT)
SDL_Log(" right");
if (event.jhat.value & SDL_HAT_DOWN)
SDL_Log(" down");
if (event.jhat.value & SDL_HAT_LEFT)
SDL_Log(" left");
SDL_Log("\n");
break;
case SDL_JOYBALLMOTION:
SDL_Log("Joystick %d ball %d delta: (%d,%d)\n",
event.jball.which,
event.jball.ball, event.jball.xrel, event.jball.yrel);
break;
case SDL_JOYBUTTONDOWN:
SDL_Log("Joystick %d button %d down\n",
event.jbutton.which, event.jbutton.button);
/* First button triggers a 0.5 second full strength rumble */
if (event.jbutton.button == 0) {
SDL_JoystickRumble(joystick, 0xFFFF, 0xFFFF, 500);
}
break;
case SDL_JOYBUTTONUP:
SDL_Log("Joystick %d button %d up\n",
event.jbutton.which, event.jbutton.button);
break;
case SDL_KEYDOWN:
/* Press the L key to lag for 3 seconds, to see what happens
when SDL doesn't service the event loop quickly. */
if (event.key.keysym.sym == SDLK_l) {
SDL_Log("Lagging for 3 seconds...\n");
SDL_Delay(3000);
break;
}
if ((event.key.keysym.sym != SDLK_ESCAPE) &&
(event.key.keysym.sym != SDLK_AC_BACK)) {
break;
}
/* Fall through to signal quit */
case SDL_FINGERDOWN:
case SDL_MOUSEBUTTONDOWN:
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
if (joystick) {
/* Update visual joystick state */
SDL_SetRenderDrawColor(screen, 0x00, 0xFF, 0x00, SDL_ALPHA_OPAQUE);
for (i = 0; i < SDL_JoystickNumButtons(joystick); ++i) {
if (SDL_JoystickGetButton(joystick, i) == SDL_PRESSED) {
DrawRect(screen, (i%20) * 34, SCREEN_HEIGHT - 68 + (i/20) * 34, 32, 32);
}
}
SDL_SetRenderDrawColor(screen, 0xFF, 0x00, 0x00, SDL_ALPHA_OPAQUE);
for (i = 0; i < SDL_JoystickNumAxes(joystick); ++i) {
/* Draw the X/Y axis */
int x, y;
x = (((int) SDL_JoystickGetAxis(joystick, i)) + 32768);
x *= SCREEN_WIDTH;
x /= 65535;
if (x < 0) {
x = 0;
} else if (x > (SCREEN_WIDTH - 16)) {
x = SCREEN_WIDTH - 16;
}
++i;
if (i < SDL_JoystickNumAxes(joystick)) {
y = (((int) SDL_JoystickGetAxis(joystick, i)) + 32768);
} else {
y = 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);
for (i = 0; i < SDL_JoystickNumHats(joystick); ++i) {
/* Derive the new position */
int x = SCREEN_WIDTH/2;
int y = SCREEN_HEIGHT/2;
const Uint8 hat_pos = SDL_JoystickGetHat(joystick, i);
if (hat_pos & SDL_HAT_UP) {
y = 0;
} else if (hat_pos & SDL_HAT_DOWN) {
y = SCREEN_HEIGHT-8;
}
if (hat_pos & SDL_HAT_LEFT) {
x = 0;
} else if (hat_pos & SDL_HAT_RIGHT) {
x = SCREEN_WIDTH-8;
}
DrawRect(screen, x, y, 8, 8);
}
}
SDL_RenderPresent(screen);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL (Note: video is required to start event loop) */
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
exit(1);
}
/* Create a window to display joystick axis position */
window = SDL_CreateWindow("Joystick Test", 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);
/* Loop, getting joystick events! */
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg(loop, NULL, 0, 1);
#else
while (!done) {
loop(NULL);
}
#endif
SDL_DestroyRenderer(screen);
SDL_DestroyWindow(window);
SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);
return 0;
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n");
return 1;
}
#endif
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testjoystick.c | C | apache-2.0 | 10,066 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Print out all the scancodes we have, just to verify them */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
int
main(int argc, char *argv[])
{
SDL_Scancode scancode;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
exit(1);
}
for (scancode = 0; scancode < SDL_NUM_SCANCODES; ++scancode) {
SDL_Log("Scancode #%d, \"%s\"\n", scancode,
SDL_GetScancodeName(scancode));
}
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testkeys.c | C | apache-2.0 | 1,124 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Test program to test dynamic loading with the loadso subsystem.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SDL.h"
typedef int (*fntype) (const char *);
int
main(int argc, char *argv[])
{
int retval = 0;
int hello = 0;
const char *libname = NULL;
const char *symname = NULL;
void *lib = NULL;
fntype fn = NULL;
if (argc != 3) {
const char *app = argv[0];
SDL_Log("USAGE: %s <library> <functionname>\n", app);
SDL_Log(" %s --hello <lib with puts()>\n", app);
return 1;
}
/* Initialize SDL */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 2;
}
if (strcmp(argv[1], "--hello") == 0) {
hello = 1;
libname = argv[2];
symname = "puts";
} else {
libname = argv[1];
symname = argv[2];
}
lib = SDL_LoadObject(libname);
if (lib == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_LoadObject('%s') failed: %s\n",
libname, SDL_GetError());
retval = 3;
} else {
fn = (fntype) SDL_LoadFunction(lib, symname);
if (fn == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_LoadFunction('%s') failed: %s\n",
symname, SDL_GetError());
retval = 4;
} else {
SDL_Log("Found %s in %s at %p\n", symname, libname, fn);
if (hello) {
SDL_Log("Calling function...\n");
fflush(stdout);
fn(" HELLO, WORLD!\n");
SDL_Log("...apparently, we survived. :)\n");
SDL_Log("Unloading library...\n");
fflush(stdout);
}
}
SDL_UnloadObject(lib);
}
SDL_Quit();
return retval;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testloadso.c | C | apache-2.0 | 2,295 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdio.h>
#include "SDL.h"
/* !!! FIXME: move this to the test framework */
static void log_locales(void)
{
SDL_Locale *locales = SDL_GetPreferredLocales();
if (locales == NULL) {
SDL_Log("Couldn't determine locales: %s", SDL_GetError());
} else {
SDL_Locale *l;
unsigned int total = 0;
SDL_Log("Locales, in order of preference:");
for (l = locales; l->language; l++) {
const char *c = l->country;
SDL_Log(" - %s%s%s", l->language, c ? "_" : "", c ? c : "");
total++;
}
SDL_Log("%u locales seen.", total);
SDL_free(locales);
}
}
int main(int argc, char **argv)
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Print locales and languages */
if (SDL_Init(SDL_INIT_VIDEO) != -1) {
log_locales();
if ((argc == 2) && (SDL_strcmp(argv[1], "--listen") == 0)) {
SDL_bool keep_going = SDL_TRUE;
while (keep_going) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
keep_going = SDL_FALSE;
} else if (e.type == SDL_LOCALECHANGED) {
SDL_Log("Saw SDL_LOCALECHANGED event!");
log_locales();
}
}
SDL_Delay(10);
}
}
SDL_Quit();
}
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testlocale.c | C | apache-2.0 | 1,977 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Test the thread and mutex locking functions
Also exercises the system's signal/thread interaction
*/
#include <signal.h>
#include <stdio.h>
#include <stdlib.h> /* for atexit() */
#include "SDL.h"
static SDL_mutex *mutex = NULL;
static SDL_threadID mainthread;
static SDL_Thread *threads[6];
static SDL_atomic_t doterminate;
/*
* SDL_Quit() shouldn't be used with atexit() directly because
* calling conventions may differ...
*/
static void
SDL_Quit_Wrapper(void)
{
SDL_Quit();
}
void
printid(void)
{
SDL_Log("Process %lu: exiting\n", SDL_ThreadID());
}
void
terminate(int sig)
{
signal(SIGINT, terminate);
SDL_AtomicSet(&doterminate, 1);
}
void
closemutex(int sig)
{
SDL_threadID id = SDL_ThreadID();
int i;
SDL_Log("Process %lu: Cleaning up...\n", id == mainthread ? 0 : id);
SDL_AtomicSet(&doterminate, 1);
for (i = 0; i < 6; ++i)
SDL_WaitThread(threads[i], NULL);
SDL_DestroyMutex(mutex);
exit(sig);
}
int SDLCALL
Run(void *data)
{
if (SDL_ThreadID() == mainthread)
signal(SIGTERM, closemutex);
while (!SDL_AtomicGet(&doterminate)) {
SDL_Log("Process %lu ready to work\n", SDL_ThreadID());
if (SDL_LockMutex(mutex) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't lock mutex: %s", SDL_GetError());
exit(1);
}
SDL_Log("Process %lu, working!\n", SDL_ThreadID());
SDL_Delay(1 * 1000);
SDL_Log("Process %lu, done!\n", SDL_ThreadID());
if (SDL_UnlockMutex(mutex) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't unlock mutex: %s", SDL_GetError());
exit(1);
}
/* If this sleep isn't done, then threads may starve */
SDL_Delay(10);
}
if (SDL_ThreadID() == mainthread && SDL_AtomicGet(&doterminate)) {
SDL_Log("Process %lu: raising SIGTERM\n", SDL_ThreadID());
raise(SIGTERM);
}
return (0);
}
int
main(int argc, char *argv[])
{
int i;
int maxproc = 6;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s\n", SDL_GetError());
exit(1);
}
atexit(SDL_Quit_Wrapper);
SDL_AtomicSet(&doterminate, 0);
if ((mutex = SDL_CreateMutex()) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create mutex: %s\n", SDL_GetError());
exit(1);
}
mainthread = SDL_ThreadID();
SDL_Log("Main thread: %lu\n", mainthread);
atexit(printid);
for (i = 0; i < maxproc; ++i) {
char name[64];
SDL_snprintf(name, sizeof (name), "Worker%d", i);
if ((threads[i] = SDL_CreateThread(Run, name, NULL)) == NULL)
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread!\n");
}
signal(SIGINT, terminate);
Run(NULL);
return (0); /* Never reached */
}
| YifuLiu/AliOS-Things | components/SDL2/test/testlock.c | C | apache-2.0 | 3,433 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL MessageBox API */
#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static int SDLCALL
button_messagebox(void *eventNumber)
{
const SDL_MessageBoxButtonData buttons[] = {
{
SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT,
0,
"OK"
},{
SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT,
1,
"Cancel"
},
};
SDL_MessageBoxData data = {
SDL_MESSAGEBOX_INFORMATION,
NULL, /* no parent window */
"Custom MessageBox",
"This is a custom messagebox",
2,
NULL,/* buttons */
NULL /* Default color scheme */
};
int button = -1;
int success = 0;
data.buttons = buttons;
if (eventNumber) {
data.message = "This is a custom messagebox from a background thread.";
}
success = SDL_ShowMessageBox(&data, &button);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
if (eventNumber) {
SDL_UserEvent event;
event.type = (intptr_t)eventNumber;
SDL_PushEvent((SDL_Event*)&event);
return 1;
} else {
quit(2);
}
}
SDL_Log("Pressed button: %d, %s\n", button, button == -1 ? "[closed]" : button == 1 ? "Cancel" : "OK");
if (eventNumber) {
SDL_UserEvent event;
event.type = (intptr_t)eventNumber;
SDL_PushEvent((SDL_Event*)&event);
}
return 0;
}
int
main(int argc, char *argv[])
{
int success;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"Simple MessageBox",
"This is a simple error MessageBox",
NULL);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
quit(1);
}
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"Simple MessageBox",
"This is a simple MessageBox with a newline:\r\nHello world!",
NULL);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
quit(1);
}
/* Google says this is Traditional Chinese for "beef with broccoli" */
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"UTF-8 Simple MessageBox",
"Unicode text: '牛肉西蘭花' ...",
NULL);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
quit(1);
}
/* Google says this is Traditional Chinese for "beef with broccoli" */
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"UTF-8 Simple MessageBox",
"Unicode text and newline:\r\n'牛肉西蘭花'\n'牛肉西蘭花'",
NULL);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
quit(1);
}
/* Google says this is Traditional Chinese for "beef with broccoli" */
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"牛肉西蘭花",
"Unicode text in the title.",
NULL);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
quit(1);
}
button_messagebox(NULL);
/* Test showing a message box from a background thread.
On Mac OS X, the video subsystem needs to be initialized for this
to work, since the message box events are dispatched by the Cocoa
subsystem on the main thread.
*/
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL video subsystem: %s\n", SDL_GetError());
return (1);
}
{
int status = 0;
SDL_Event event;
intptr_t eventNumber = SDL_RegisterEvents(1);
SDL_Thread* thread = SDL_CreateThread(&button_messagebox, "MessageBox", (void*)eventNumber);
while (SDL_WaitEvent(&event))
{
if (event.type == eventNumber) {
break;
}
}
SDL_WaitThread(thread, &status);
SDL_Log("Message box thread return %i\n", status);
}
/* Test showing a message box with a parent window */
{
SDL_Event event;
SDL_Window *window = SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
success = SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"Simple MessageBox",
"This is a simple error MessageBox with a parent window",
window);
if (success == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error Presenting MessageBox: %s\n", SDL_GetError());
quit(1);
}
while (SDL_WaitEvent(&event))
{
if (event.type == SDL_QUIT || event.type == SDL_KEYUP) {
break;
}
}
}
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testmessage.c | C | apache-2.0 | 5,914 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "SDL.h"
#include <stdio.h> /* for fflush() and stdout */
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
static SDL_AudioSpec spec;
static Uint8 *sound = NULL; /* Pointer to wave data */
static Uint32 soundlen = 0; /* Length of wave data */
typedef struct
{
SDL_AudioDeviceID dev;
int soundpos;
SDL_atomic_t done;
} callback_data;
callback_data cbd[64];
void SDLCALL
play_through_once(void *arg, Uint8 * stream, int len)
{
callback_data *cbd = (callback_data *) arg;
Uint8 *waveptr = sound + cbd->soundpos;
int waveleft = soundlen - cbd->soundpos;
int cpy = len;
if (cpy > waveleft)
cpy = waveleft;
SDL_memcpy(stream, waveptr, cpy);
len -= cpy;
cbd->soundpos += cpy;
if (len > 0) {
stream += cpy;
SDL_memset(stream, spec.silence, len);
SDL_AtomicSet(&cbd->done, 1);
}
}
void
loop()
{
if (SDL_AtomicGet(&cbd[0].done)) {
#ifdef __EMSCRIPTEN__
emscripten_cancel_main_loop();
#endif
SDL_PauseAudioDevice(cbd[0].dev, 1);
SDL_CloseAudioDevice(cbd[0].dev);
SDL_FreeWAV(sound);
SDL_Quit();
}
}
static void
test_multi_audio(int devcount)
{
int keep_going = 1;
int i;
#ifdef __ANDROID__
SDL_Event event;
/* Create a Window to get fully initialized event processing for testing pause on Android. */
SDL_CreateWindow("testmultiaudio", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 320, 240, 0);
#endif
if (devcount > 64) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Too many devices (%d), clamping to 64...\n",
devcount);
devcount = 64;
}
spec.callback = play_through_once;
for (i = 0; i < devcount; i++) {
const char *devname = SDL_GetAudioDeviceName(i, 0);
SDL_Log("playing on device #%d: ('%s')...", i, devname);
fflush(stdout);
SDL_memset(&cbd[0], '\0', sizeof(callback_data));
spec.userdata = &cbd[0];
cbd[0].dev = SDL_OpenAudioDevice(devname, 0, &spec, NULL, 0);
if (cbd[0].dev == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Open device failed: %s\n", SDL_GetError());
} else {
SDL_PauseAudioDevice(cbd[0].dev, 0);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!SDL_AtomicGet(&cbd[0].done)) {
#ifdef __ANDROID__
/* Empty queue, some application events would prevent pause. */
while (SDL_PollEvent(&event)){}
#endif
SDL_Delay(100);
}
SDL_PauseAudioDevice(cbd[0].dev, 1);
#endif
SDL_Log("done.\n");
SDL_CloseAudioDevice(cbd[0].dev);
}
}
SDL_memset(cbd, '\0', sizeof(cbd));
SDL_Log("playing on all devices...\n");
for (i = 0; i < devcount; i++) {
const char *devname = SDL_GetAudioDeviceName(i, 0);
spec.userdata = &cbd[i];
cbd[i].dev = SDL_OpenAudioDevice(devname, 0, &spec, NULL, 0);
if (cbd[i].dev == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Open device %d failed: %s\n", i, SDL_GetError());
}
}
for (i = 0; i < devcount; i++) {
if (cbd[i].dev) {
SDL_PauseAudioDevice(cbd[i].dev, 0);
}
}
while (keep_going) {
keep_going = 0;
for (i = 0; i < devcount; i++) {
if ((cbd[i].dev) && (!SDL_AtomicGet(&cbd[i].done))) {
keep_going = 1;
}
}
#ifdef __ANDROID__
/* Empty queue, some application events would prevent pause. */
while (SDL_PollEvent(&event)){}
#endif
SDL_Delay(100);
}
#ifndef __EMSCRIPTEN__
for (i = 0; i < devcount; i++) {
if (cbd[i].dev) {
SDL_PauseAudioDevice(cbd[i].dev, 1);
SDL_CloseAudioDevice(cbd[i].dev);
}
}
SDL_Log("All done!\n");
#endif
}
int
main(int argc, char **argv)
{
int devcount = 0;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver());
devcount = SDL_GetNumAudioDevices(0);
if (devcount < 1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Don't see any specific audio devices!\n");
} else {
if (argv[1] == NULL) {
argv[1] = "sample.wav";
}
/* Load the wave file into memory */
if (SDL_LoadWAV(argv[1], &spec, &sound, &soundlen) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", argv[1],
SDL_GetError());
} else {
test_multi_audio(devcount);
SDL_FreeWAV(sound);
}
}
SDL_Quit();
return 0;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testmultiaudio.c | C | apache-2.0 | 5,516 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Create a native window and attach an SDL renderer */
#include <stdio.h>
#include <stdlib.h> /* for srand() */
#include <time.h> /* for time() */
#include "testnative.h"
#define WINDOW_W 640
#define WINDOW_H 480
#define NUM_SPRITES 100
#define MAX_SPEED 1
static NativeWindowFactory *factories[] = {
#ifdef TEST_NATIVE_WINDOWS
&WindowsWindowFactory,
#endif
#ifdef TEST_NATIVE_X11
&X11WindowFactory,
#endif
#ifdef TEST_NATIVE_COCOA
&CocoaWindowFactory,
#endif
NULL
};
static NativeWindowFactory *factory = NULL;
static void *native_window;
static SDL_Rect *positions, *velocities;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_VideoQuit();
if (native_window) {
factory->DestroyNativeWindow(native_window);
}
exit(rc);
}
SDL_Texture *
LoadSprite(SDL_Renderer *renderer, char *file)
{
SDL_Surface *temp;
SDL_Texture *sprite;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return 0;
}
/* Set transparent pixel as the pixel at (0,0) */
if (temp->format->palette) {
SDL_SetColorKey(temp, 1, *(Uint8 *) temp->pixels);
}
/* Create textures from the image */
sprite = SDL_CreateTextureFromSurface(renderer, temp);
if (!sprite) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return 0;
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return sprite;
}
void
MoveSprites(SDL_Renderer * renderer, SDL_Texture * sprite)
{
int sprite_w, sprite_h;
int i;
SDL_Rect viewport;
SDL_Rect *position, *velocity;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
SDL_QueryTexture(sprite, NULL, NULL, &sprite_w, &sprite_h);
/* Draw a gray background */
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
/* Move the sprite, bounce at the wall, and draw */
for (i = 0; i < NUM_SPRITES; ++i) {
position = &positions[i];
velocity = &velocities[i];
position->x += velocity->x;
if ((position->x < 0) || (position->x >= (viewport.w - sprite_w))) {
velocity->x = -velocity->x;
position->x += velocity->x;
}
position->y += velocity->y;
if ((position->y < 0) || (position->y >= (viewport.h - sprite_h))) {
velocity->y = -velocity->y;
position->y += velocity->y;
}
/* Blit the sprite onto the screen */
SDL_RenderCopy(renderer, sprite, NULL, position);
}
/* Update the screen! */
SDL_RenderPresent(renderer);
}
int
main(int argc, char *argv[])
{
int i, done;
const char *driver;
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *sprite;
int window_w, window_h;
int sprite_w, sprite_h;
SDL_Event event;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_VideoInit(NULL) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL video: %s\n",
SDL_GetError());
exit(1);
}
driver = SDL_GetCurrentVideoDriver();
/* Find a native window driver and create a native window */
for (i = 0; factories[i]; ++i) {
if (SDL_strcmp(driver, factories[i]->tag) == 0) {
factory = factories[i];
break;
}
}
if (!factory) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't find native window code for %s driver\n",
driver);
quit(2);
}
SDL_Log("Creating native window for %s driver\n", driver);
native_window = factory->CreateNativeWindow(WINDOW_W, WINDOW_H);
if (!native_window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create native window\n");
quit(3);
}
window = SDL_CreateWindowFrom(native_window);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create SDL window: %s\n", SDL_GetError());
quit(4);
}
SDL_SetWindowTitle(window, "SDL Native Window Test");
/* Create the renderer */
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
quit(5);
}
/* Clear the window, load the sprite and go! */
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
sprite = LoadSprite(renderer, "icon.bmp");
if (!sprite) {
quit(6);
}
/* Allocate memory for the sprite info */
SDL_GetWindowSize(window, &window_w, &window_h);
SDL_QueryTexture(sprite, NULL, NULL, &sprite_w, &sprite_h);
positions = (SDL_Rect *) SDL_malloc(NUM_SPRITES * sizeof(SDL_Rect));
velocities = (SDL_Rect *) SDL_malloc(NUM_SPRITES * sizeof(SDL_Rect));
if (!positions || !velocities) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
quit(2);
}
srand(time(NULL));
for (i = 0; i < NUM_SPRITES; ++i) {
positions[i].x = rand() % (window_w - sprite_w);
positions[i].y = rand() % (window_h - sprite_h);
positions[i].w = sprite_w;
positions[i].h = sprite_h;
velocities[i].x = 0;
velocities[i].y = 0;
while (!velocities[i].x && !velocities[i].y) {
velocities[i].x = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
velocities[i].y = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
}
}
/* Main render loop */
done = 0;
while (!done) {
/* Check for events */
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_WINDOWEVENT:
switch (event.window.event) {
case SDL_WINDOWEVENT_EXPOSED:
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
break;
}
break;
case SDL_QUIT:
done = 1;
break;
default:
break;
}
}
MoveSprites(renderer, sprite);
}
quit(0);
return 0; /* to prevent compiler warning */
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testnative.c | C | apache-2.0 | 6,979 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Definitions for platform dependent windowing functions to test SDL
integration with native windows
*/
#include "SDL.h"
/* This header includes all the necessary system headers for native windows */
#include "SDL_syswm.h"
typedef struct
{
const char *tag;
void *(*CreateNativeWindow) (int w, int h);
void (*DestroyNativeWindow) (void *window);
} NativeWindowFactory;
#ifdef SDL_VIDEO_DRIVER_WINDOWS
#define TEST_NATIVE_WINDOWS
extern NativeWindowFactory WindowsWindowFactory;
#endif
#ifdef SDL_VIDEO_DRIVER_X11
#define TEST_NATIVE_X11
extern NativeWindowFactory X11WindowFactory;
#endif
#ifdef SDL_VIDEO_DRIVER_COCOA
/* Actually, we don't really do this, since it involves adding Objective C
support to the build system, which is a little tricky. You can uncomment
it manually though and link testnativecocoa.m into the test application.
*/
#define TEST_NATIVE_COCOA
extern NativeWindowFactory CocoaWindowFactory;
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testnative.h | C | apache-2.0 | 1,357 |
#include "testnative.h"
#ifdef TEST_NATIVE_COCOA
#include <Cocoa/Cocoa.h>
static void *CreateWindowCocoa(int w, int h);
static void DestroyWindowCocoa(void *window);
NativeWindowFactory CocoaWindowFactory = {
"cocoa",
CreateWindowCocoa,
DestroyWindowCocoa
};
static void *CreateWindowCocoa(int w, int h)
{
NSAutoreleasePool *pool;
NSWindow *nswindow;
NSRect rect;
unsigned int style;
pool = [[NSAutoreleasePool alloc] init];
rect.origin.x = 0;
rect.origin.y = 0;
rect.size.width = w;
rect.size.height = h;
rect.origin.y = CGDisplayPixelsHigh(kCGDirectMainDisplay) - rect.origin.y - rect.size.height;
style = (NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask);
nswindow = [[NSWindow alloc] initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:FALSE];
[nswindow makeKeyAndOrderFront:nil];
[pool release];
return nswindow;
}
static void DestroyWindowCocoa(void *window)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSWindow *nswindow = (NSWindow *)window;
[nswindow close];
[pool release];
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testnativecocoa.m | Objective-C | apache-2.0 | 1,159 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "testnative.h"
#ifdef TEST_NATIVE_WINDOWS
static void *CreateWindowNative(int w, int h);
static void DestroyWindowNative(void *window);
NativeWindowFactory WindowsWindowFactory = {
"windows",
CreateWindowNative,
DestroyWindowNative
};
LRESULT CALLBACK
WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
static void *
CreateWindowNative(int w, int h)
{
HWND hwnd;
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = GetModuleHandle(NULL);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = "SDL Test";
if (!RegisterClass(&wc)) {
MessageBox(NULL, "Window Registration Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
hwnd =
CreateWindow("SDL Test", "", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
CW_USEDEFAULT, w, h, NULL, NULL, GetModuleHandle(NULL),
NULL);
if (hwnd == NULL) {
MessageBox(NULL, "Window Creation Failed!", "Error!",
MB_ICONEXCLAMATION | MB_OK);
return 0;
}
ShowWindow(hwnd, SW_SHOW);
return hwnd;
}
static void
DestroyWindowNative(void *window)
{
DestroyWindow((HWND) window);
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testnativew32.c | C | apache-2.0 | 2,073 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "testnative.h"
#ifdef TEST_NATIVE_X11
static void *CreateWindowX11(int w, int h);
static void DestroyWindowX11(void *window);
NativeWindowFactory X11WindowFactory = {
"x11",
CreateWindowX11,
DestroyWindowX11
};
static Display *dpy;
static void *
CreateWindowX11(int w, int h)
{
Window window = 0;
dpy = XOpenDisplay(NULL);
if (dpy) {
window =
XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, w, h, 0, 0,
0);
XMapRaised(dpy, window);
XSync(dpy, False);
}
return (void *) window;
}
static void
DestroyWindowX11(void *window)
{
if (dpy) {
XDestroyWindow(dpy, (Window) window);
XCloseDisplay(dpy);
}
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testnativex11.c | C | apache-2.0 | 1,158 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: picks the offscreen backend and renders each frame to a bmp */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#include "SDL_stdinc.h"
#include "SDL_opengl.h"
static SDL_Renderer *renderer = NULL;
static SDL_Window *window = NULL;
static int done = SDL_FALSE;
static int frame_number = 0;
static int width = 640;
static int height = 480;
static int max_frames = 200;
void
draw()
{
SDL_Rect Rect;
SDL_SetRenderDrawColor(renderer, 0x10, 0x9A, 0xCE, 0xFF);
SDL_RenderClear(renderer);
/* Grow based on the frame just to show a difference per frame of the region */
Rect.x = 0;
Rect.y = 0;
Rect.w = (frame_number * 2) % width;
Rect.h = (frame_number * 2) % height;
SDL_SetRenderDrawColor(renderer, 0xFF, 0x10, 0x21, 0xFF);
SDL_RenderFillRect(renderer, &Rect);
SDL_RenderPresent(renderer);
}
void
save_surface_to_bmp()
{
SDL_Surface* surface;
Uint32 r_mask, g_mask, b_mask, a_mask;
Uint32 pixel_format;
char file[128];
int bbp;
pixel_format = SDL_GetWindowPixelFormat(window);
SDL_PixelFormatEnumToMasks(pixel_format, &bbp, &r_mask, &g_mask, &b_mask, &a_mask);
surface = SDL_CreateRGBSurface(0, width, height, bbp, r_mask, g_mask, b_mask, a_mask);
SDL_RenderReadPixels(renderer, NULL, pixel_format, (void*)surface->pixels, surface->pitch);
SDL_snprintf(file, sizeof(file), "SDL_window%d-%8.8d.bmp",
SDL_GetWindowID(window), ++frame_number);
SDL_SaveBMP(surface, file);
SDL_FreeSurface(surface);
}
void
loop()
{
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
done = SDL_TRUE;
break;
}
}
draw();
save_surface_to_bmp();
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
Uint32 then, now, frames;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Force the offscreen renderer, if it cannot be created then fail out */
if (SDL_VideoInit("offscreen") < 0) {
SDL_Log("Couldn't initialize the offscreen video driver: %s\n",
SDL_GetError());
return SDL_FALSE;
}
/* If OPENGL fails to init it will fallback to using a framebuffer for rendering */
window = SDL_CreateWindow("Offscreen Test",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
width, height, 0);
if (!window) {
SDL_Log("Couldn't create window: %s\n",
SDL_GetError());
return SDL_FALSE;
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
SDL_Log("Couldn't create renderer: %s\n",
SDL_GetError());
return SDL_FALSE;
}
SDL_RenderClear(renderer);
srand((unsigned int)time(NULL));
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
SDL_Log("Rendering %i frames offscreen\n", max_frames);
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done && frames < max_frames) {
++frames;
loop();
/* Print out some timing information, along with remaining frames */
if (frames % (max_frames / 10) == 0) {
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("Frames remaining: %i rendering at %2.2f frames per second\n", max_frames - frames, fps);
}
}
}
#endif
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testoffscreen.c | C | apache-2.0 | 4,277 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/********************************************************************************
* *
* Test of the overlay used for moved pictures, test more closed to real life. *
* Running trojan moose :) Coded by Mike Gorchak. *
* *
********************************************************************************/
#include <stdlib.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#include "testyuv_cvt.h"
#define MOOSEPIC_W 64
#define MOOSEPIC_H 88
#define MOOSEFRAME_SIZE (MOOSEPIC_W * MOOSEPIC_H)
#define MOOSEFRAMES_COUNT 10
SDL_Color MooseColors[84] = {
{49, 49, 49, SDL_ALPHA_OPAQUE}
, {66, 24, 0, SDL_ALPHA_OPAQUE}
, {66, 33, 0, SDL_ALPHA_OPAQUE}
, {66, 66, 66, SDL_ALPHA_OPAQUE}
,
{66, 115, 49, SDL_ALPHA_OPAQUE}
, {74, 33, 0, SDL_ALPHA_OPAQUE}
, {74, 41, 16, SDL_ALPHA_OPAQUE}
, {82, 33, 8, SDL_ALPHA_OPAQUE}
,
{82, 41, 8, SDL_ALPHA_OPAQUE}
, {82, 49, 16, SDL_ALPHA_OPAQUE}
, {82, 82, 82, SDL_ALPHA_OPAQUE}
, {90, 41, 8, SDL_ALPHA_OPAQUE}
,
{90, 41, 16, SDL_ALPHA_OPAQUE}
, {90, 57, 24, SDL_ALPHA_OPAQUE}
, {99, 49, 16, SDL_ALPHA_OPAQUE}
, {99, 66, 24, SDL_ALPHA_OPAQUE}
,
{99, 66, 33, SDL_ALPHA_OPAQUE}
, {99, 74, 33, SDL_ALPHA_OPAQUE}
, {107, 57, 24, SDL_ALPHA_OPAQUE}
, {107, 82, 41, SDL_ALPHA_OPAQUE}
,
{115, 57, 33, SDL_ALPHA_OPAQUE}
, {115, 66, 33, SDL_ALPHA_OPAQUE}
, {115, 66, 41, SDL_ALPHA_OPAQUE}
, {115, 74, 0, SDL_ALPHA_OPAQUE}
,
{115, 90, 49, SDL_ALPHA_OPAQUE}
, {115, 115, 115, SDL_ALPHA_OPAQUE}
, {123, 82, 0, SDL_ALPHA_OPAQUE}
, {123, 99, 57, SDL_ALPHA_OPAQUE}
,
{132, 66, 41, SDL_ALPHA_OPAQUE}
, {132, 74, 41, SDL_ALPHA_OPAQUE}
, {132, 90, 8, SDL_ALPHA_OPAQUE}
, {132, 99, 33, SDL_ALPHA_OPAQUE}
,
{132, 99, 66, SDL_ALPHA_OPAQUE}
, {132, 107, 66, SDL_ALPHA_OPAQUE}
, {140, 74, 49, SDL_ALPHA_OPAQUE}
, {140, 99, 16, SDL_ALPHA_OPAQUE}
,
{140, 107, 74, SDL_ALPHA_OPAQUE}
, {140, 115, 74, SDL_ALPHA_OPAQUE}
, {148, 107, 24, SDL_ALPHA_OPAQUE}
, {148, 115, 82, SDL_ALPHA_OPAQUE}
,
{148, 123, 74, SDL_ALPHA_OPAQUE}
, {148, 123, 90, SDL_ALPHA_OPAQUE}
, {156, 115, 33, SDL_ALPHA_OPAQUE}
, {156, 115, 90, SDL_ALPHA_OPAQUE}
,
{156, 123, 82, SDL_ALPHA_OPAQUE}
, {156, 132, 82, SDL_ALPHA_OPAQUE}
, {156, 132, 99, SDL_ALPHA_OPAQUE}
, {156, 156, 156, SDL_ALPHA_OPAQUE}
,
{165, 123, 49, SDL_ALPHA_OPAQUE}
, {165, 123, 90, SDL_ALPHA_OPAQUE}
, {165, 132, 82, SDL_ALPHA_OPAQUE}
, {165, 132, 90, SDL_ALPHA_OPAQUE}
,
{165, 132, 99, SDL_ALPHA_OPAQUE}
, {165, 140, 90, SDL_ALPHA_OPAQUE}
, {173, 132, 57, SDL_ALPHA_OPAQUE}
, {173, 132, 99, SDL_ALPHA_OPAQUE}
,
{173, 140, 107, SDL_ALPHA_OPAQUE}
, {173, 140, 115, SDL_ALPHA_OPAQUE}
, {173, 148, 99, SDL_ALPHA_OPAQUE}
, {173, 173, 173, SDL_ALPHA_OPAQUE}
,
{181, 140, 74, SDL_ALPHA_OPAQUE}
, {181, 148, 115, SDL_ALPHA_OPAQUE}
, {181, 148, 123, SDL_ALPHA_OPAQUE}
, {181, 156, 107, SDL_ALPHA_OPAQUE}
,
{189, 148, 123, SDL_ALPHA_OPAQUE}
, {189, 156, 82, SDL_ALPHA_OPAQUE}
, {189, 156, 123, SDL_ALPHA_OPAQUE}
, {189, 156, 132, SDL_ALPHA_OPAQUE}
,
{189, 189, 189, SDL_ALPHA_OPAQUE}
, {198, 156, 123, SDL_ALPHA_OPAQUE}
, {198, 165, 132, SDL_ALPHA_OPAQUE}
, {206, 165, 99, SDL_ALPHA_OPAQUE}
,
{206, 165, 132, SDL_ALPHA_OPAQUE}
, {206, 173, 140, SDL_ALPHA_OPAQUE}
, {206, 206, 206, SDL_ALPHA_OPAQUE}
, {214, 173, 115, SDL_ALPHA_OPAQUE}
,
{214, 173, 140, SDL_ALPHA_OPAQUE}
, {222, 181, 148, SDL_ALPHA_OPAQUE}
, {222, 189, 132, SDL_ALPHA_OPAQUE}
, {222, 189, 156, SDL_ALPHA_OPAQUE}
,
{222, 222, 222, SDL_ALPHA_OPAQUE}
, {231, 198, 165, SDL_ALPHA_OPAQUE}
, {231, 231, 231, SDL_ALPHA_OPAQUE}
, {239, 206, 173, SDL_ALPHA_OPAQUE}
};
Uint8 MooseFrame[MOOSEFRAMES_COUNT][MOOSEFRAME_SIZE*2];
SDL_Texture *MooseTexture;
SDL_Rect displayrect;
int window_w;
int window_h;
SDL_Window *window;
SDL_Renderer *renderer;
int paused = 0;
int i;
SDL_bool done = SDL_FALSE;
static int fpsdelay;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static void
PrintUsage(char *argv0)
{
SDL_Log("Usage: %s [arg] [arg] [arg] ...\n", argv0);
SDL_Log("\n");
SDL_Log("Where 'arg' is any of the following options:\n");
SDL_Log("\n");
SDL_Log(" -fps <frames per second>\n");
SDL_Log(" -nodelay\n");
SDL_Log(" -format <fmt> (one of the: YV12, IYUV, YUY2, UYVY, YVYU)\n");
SDL_Log(" -scale <scale factor> (initial scale of the overlay)\n");
SDL_Log(" -help (shows this help)\n");
SDL_Log("\n");
SDL_Log("Press ESC to exit, or SPACE to freeze the movie while application running.\n");
SDL_Log("\n");
}
void
loop()
{
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
SDL_RenderSetViewport(renderer, NULL);
displayrect.w = window_w = event.window.data1;
displayrect.h = window_h = event.window.data2;
}
break;
case SDL_MOUSEBUTTONDOWN:
displayrect.x = event.button.x - window_w / 2;
displayrect.y = event.button.y - window_h / 2;
break;
case SDL_MOUSEMOTION:
if (event.motion.state) {
displayrect.x = event.motion.x - window_w / 2;
displayrect.y = event.motion.y - window_h / 2;
}
break;
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_SPACE) {
paused = !paused;
break;
}
if (event.key.keysym.sym != SDLK_ESCAPE) {
break;
}
case SDL_QUIT:
done = SDL_TRUE;
break;
}
}
#ifndef __EMSCRIPTEN__
SDL_Delay(fpsdelay);
#endif
if (!paused) {
i = (i + 1) % MOOSEFRAMES_COUNT;
SDL_UpdateTexture(MooseTexture, NULL, MooseFrame[i], MOOSEPIC_W);
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, MooseTexture, NULL, &displayrect);
SDL_RenderPresent(renderer);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char **argv)
{
Uint8 *RawMooseData;
SDL_RWops *handle;
SDL_Window *window;
int j;
int fps = 12;
int nodelay = 0;
int scale = 5;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 3;
}
while (argc > 1) {
if (SDL_strcmp(argv[1], "-fps") == 0) {
if (argv[2]) {
fps = SDL_atoi(argv[2]);
if (fps == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"The -fps option requires an argument [from 1 to 1000], default is 12.\n");
quit(10);
}
if ((fps < 0) || (fps > 1000)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"The -fps option must be in range from 1 to 1000, default is 12.\n");
quit(10);
}
argv += 2;
argc -= 2;
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"The -fps option requires an argument [from 1 to 1000], default is 12.\n");
quit(10);
}
} else if (SDL_strcmp(argv[1], "-nodelay") == 0) {
nodelay = 1;
argv += 1;
argc -= 1;
} else if (SDL_strcmp(argv[1], "-scale") == 0) {
if (argv[2]) {
scale = SDL_atoi(argv[2]);
if (scale == 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"The -scale option requires an argument [from 1 to 50], default is 5.\n");
quit(10);
}
if ((scale < 0) || (scale > 50)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"The -scale option must be in range from 1 to 50, default is 5.\n");
quit(10);
}
argv += 2;
argc -= 2;
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"The -fps option requires an argument [from 1 to 1000], default is 12.\n");
quit(10);
}
} else if ((SDL_strcmp(argv[1], "-help") == 0)
|| (SDL_strcmp(argv[1], "-h") == 0)) {
PrintUsage(argv[0]);
quit(0);
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unrecognized option: %s.\n", argv[1]);
quit(10);
}
break;
}
RawMooseData = (Uint8 *) SDL_malloc(MOOSEFRAME_SIZE * MOOSEFRAMES_COUNT);
if (RawMooseData == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Can't allocate memory for movie !\n");
quit(1);
}
/* load the trojan moose images */
handle = SDL_RWFromFile("moose.dat", "rb");
if (handle == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Can't find the file moose.dat !\n");
SDL_free(RawMooseData);
quit(2);
}
SDL_RWread(handle, RawMooseData, MOOSEFRAME_SIZE, MOOSEFRAMES_COUNT);
SDL_RWclose(handle);
/* Create the window and renderer */
window_w = MOOSEPIC_W * scale;
window_h = MOOSEPIC_H * scale;
window = SDL_CreateWindow("Happy Moose",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
window_w, window_h,
SDL_WINDOW_RESIZABLE);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create window: %s\n", SDL_GetError());
SDL_free(RawMooseData);
quit(4);
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create renderer: %s\n", SDL_GetError());
SDL_free(RawMooseData);
quit(4);
}
MooseTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, MOOSEPIC_W, MOOSEPIC_H);
if (!MooseTexture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
SDL_free(RawMooseData);
quit(5);
}
/* Uncomment this to check vertex color with a YUV texture */
/* SDL_SetTextureColorMod(MooseTexture, 0xff, 0x80, 0x80); */
for (i = 0; i < MOOSEFRAMES_COUNT; i++) {
Uint8 MooseFrameRGB[MOOSEFRAME_SIZE*3];
Uint8 *rgb;
Uint8 *frame;
rgb = MooseFrameRGB;
frame = RawMooseData + i * MOOSEFRAME_SIZE;
for (j = 0; j < MOOSEFRAME_SIZE; ++j) {
rgb[0] = MooseColors[frame[j]].r;
rgb[1] = MooseColors[frame[j]].g;
rgb[2] = MooseColors[frame[j]].b;
rgb += 3;
}
ConvertRGBtoYUV(SDL_PIXELFORMAT_YV12, MooseFrameRGB, MOOSEPIC_W*3, MooseFrame[i], MOOSEPIC_W, MOOSEPIC_H,
SDL_GetYUVConversionModeForResolution(MOOSEPIC_W, MOOSEPIC_H),
0, 100);
}
SDL_free(RawMooseData);
/* set the start frame */
i = 0;
if (nodelay) {
fpsdelay = 0;
} else {
fpsdelay = 1000 / fps;
}
displayrect.x = 0;
displayrect.y = 0;
displayrect.w = window_w;
displayrect.h = window_h;
/* Ignore key up events, they don't even get filtered */
SDL_EventState(SDL_KEYUP, SDL_IGNORE);
/* Loop, waiting for QUIT or RESIZE */
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, nodelay ? 0 : fps, 1);
#else
while (!done) {
loop();
}
#endif
SDL_DestroyRenderer(renderer);
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testoverlay2.c | C | apache-2.0 | 12,936 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdio.h>
#include "SDL.h"
/*
* Watcom C flags these as Warning 201: "Unreachable code" if you just
* compare them directly, so we push it through a function to keep the
* compiler quiet. --ryan.
*/
static int
badsize(size_t sizeoftype, size_t hardcodetype)
{
return sizeoftype != hardcodetype;
}
int
TestTypes(SDL_bool verbose)
{
int error = 0;
SDL_COMPILE_TIME_ASSERT(SDL_MAX_SINT8, SDL_MAX_SINT8 == 127);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_SINT8, SDL_MIN_SINT8 == -128);
SDL_COMPILE_TIME_ASSERT(SDL_MAX_UINT8, SDL_MAX_UINT8 == 255);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_UINT8, SDL_MIN_UINT8 == 0);
SDL_COMPILE_TIME_ASSERT(SDL_MAX_SINT16, SDL_MAX_SINT16 == 32767);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_SINT16, SDL_MIN_SINT16 == -32768);
SDL_COMPILE_TIME_ASSERT(SDL_MAX_UINT16, SDL_MAX_UINT16 == 65535);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_UINT16, SDL_MIN_UINT16 == 0);
SDL_COMPILE_TIME_ASSERT(SDL_MAX_SINT32, SDL_MAX_SINT32 == 2147483647);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_SINT32, SDL_MIN_SINT32 == ~0x7fffffff); /* Instead of -2147483648, which is treated as unsigned by some compilers */
SDL_COMPILE_TIME_ASSERT(SDL_MAX_UINT32, SDL_MAX_UINT32 == 4294967295u);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_UINT32, SDL_MIN_UINT32 == 0);
SDL_COMPILE_TIME_ASSERT(SDL_MAX_SINT64, SDL_MAX_SINT64 == 9223372036854775807ll);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_SINT64, SDL_MIN_SINT64 == ~0x7fffffffffffffffll); /* Instead of -9223372036854775808, which is treated as unsigned by compilers */
SDL_COMPILE_TIME_ASSERT(SDL_MAX_UINT64, SDL_MAX_UINT64 == 18446744073709551615ull);
SDL_COMPILE_TIME_ASSERT(SDL_MIN_UINT64, SDL_MIN_UINT64 == 0);
if (badsize(sizeof(Uint8), 1)) {
if (verbose)
SDL_Log("sizeof(Uint8) != 1, instead = %u\n",
(unsigned int)sizeof(Uint8));
++error;
}
if (badsize(sizeof(Uint16), 2)) {
if (verbose)
SDL_Log("sizeof(Uint16) != 2, instead = %u\n",
(unsigned int)sizeof(Uint16));
++error;
}
if (badsize(sizeof(Uint32), 4)) {
if (verbose)
SDL_Log("sizeof(Uint32) != 4, instead = %u\n",
(unsigned int)sizeof(Uint32));
++error;
}
if (badsize(sizeof(Uint64), 8)) {
if (verbose)
SDL_Log("sizeof(Uint64) != 8, instead = %u\n",
(unsigned int)sizeof(Uint64));
++error;
}
if (verbose && !error)
SDL_Log("All data types are the expected size.\n");
return (error ? 1 : 0);
}
int
TestEndian(SDL_bool verbose)
{
int error = 0;
Uint16 value = 0x1234;
int real_byteorder;
Uint16 value16 = 0xCDAB;
Uint16 swapped16 = 0xABCD;
Uint32 value32 = 0xEFBEADDE;
Uint32 swapped32 = 0xDEADBEEF;
Uint64 value64, swapped64;
value64 = 0xEFBEADDE;
value64 <<= 32;
value64 |= 0xCDAB3412;
swapped64 = 0x1234ABCD;
swapped64 <<= 32;
swapped64 |= 0xDEADBEEF;
if (verbose) {
SDL_Log("Detected a %s endian machine.\n",
(SDL_BYTEORDER == SDL_LIL_ENDIAN) ? "little" : "big");
}
if ((*((char *) &value) >> 4) == 0x1) {
real_byteorder = SDL_BIG_ENDIAN;
} else {
real_byteorder = SDL_LIL_ENDIAN;
}
if (real_byteorder != SDL_BYTEORDER) {
if (verbose) {
SDL_Log("Actually a %s endian machine!\n",
(real_byteorder == SDL_LIL_ENDIAN) ? "little" : "big");
}
++error;
}
if (verbose) {
SDL_Log("Value 16 = 0x%X, swapped = 0x%X\n", value16,
SDL_Swap16(value16));
}
if (SDL_Swap16(value16) != swapped16) {
if (verbose) {
SDL_Log("16 bit value swapped incorrectly!\n");
}
++error;
}
if (verbose) {
SDL_Log("Value 32 = 0x%X, swapped = 0x%X\n", value32,
SDL_Swap32(value32));
}
if (SDL_Swap32(value32) != swapped32) {
if (verbose) {
SDL_Log("32 bit value swapped incorrectly!\n");
}
++error;
}
if (verbose) {
SDL_Log("Value 64 = 0x%"SDL_PRIX64", swapped = 0x%"SDL_PRIX64"\n", value64,
SDL_Swap64(value64));
}
if (SDL_Swap64(value64) != swapped64) {
if (verbose) {
SDL_Log("64 bit value swapped incorrectly!\n");
}
++error;
}
return (error ? 1 : 0);
}
static int TST_allmul (void *a, void *b, int arg, void *result, void *expected)
{
(*(long long *)result) = ((*(long long *)a) * (*(long long *)b));
return (*(long long *)result) == (*(long long *)expected);
}
static int TST_alldiv (void *a, void *b, int arg, void *result, void *expected)
{
(*(long long *)result) = ((*(long long *)a) / (*(long long *)b));
return (*(long long *)result) == (*(long long *)expected);
}
static int TST_allrem (void *a, void *b, int arg, void *result, void *expected)
{
(*(long long *)result) = ((*(long long *)a) % (*(long long *)b));
return (*(long long *)result) == (*(long long *)expected);
}
static int TST_ualldiv (void *a, void *b, int arg, void *result, void *expected)
{
(*(unsigned long long *)result) = ((*(unsigned long long *)a) / (*(unsigned long long *)b));
return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
}
static int TST_uallrem (void *a, void *b, int arg, void *result, void *expected)
{
(*(unsigned long long *)result) = ((*(unsigned long long *)a) % (*(unsigned long long *)b));
return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
}
static int TST_allshl (void *a, void *b, int arg, void *result, void *expected)
{
(*(long long *)result) = (*(long long *)a) << arg;
return (*(long long *)result) == (*(long long *)expected);
}
static int TST_aullshl (void *a, void *b, int arg, void *result, void *expected)
{
(*(unsigned long long *)result) = (*(unsigned long long *)a) << arg;
return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
}
static int TST_allshr (void *a, void *b, int arg, void *result, void *expected)
{
(*(long long *)result) = (*(long long *)a) >> arg;
return (*(long long *)result) == (*(long long *)expected);
}
static int TST_aullshr (void *a, void *b, int arg, void *result, void *expected)
{
(*(unsigned long long *)result) = (*(unsigned long long *)a) >> arg;
return (*(unsigned long long *)result) == (*(unsigned long long *)expected);
}
typedef int (*LL_Intrinsic)(void *a, void *b, int arg, void *result, void *expected);
typedef struct {
const char *operation;
LL_Intrinsic routine;
unsigned long long a, b;
int arg;
unsigned long long expected_result;
} LL_Test;
static LL_Test LL_Tests[] =
{
/* UNDEFINED {"_allshl", &TST_allshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 65, 0x0000000000000000ll}, */
{"_allshl", &TST_allshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 1, 0xFFFFFFFFFFFFFFFEll},
{"_allshl", &TST_allshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 32, 0xFFFFFFFF00000000ll},
{"_allshl", &TST_allshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 33, 0xFFFFFFFE00000000ll},
{"_allshl", &TST_allshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 0, 0xFFFFFFFFFFFFFFFFll},
{"_allshr", &TST_allshr, 0xAAAAAAAA55555555ll, 0ll, 63, 0xFFFFFFFFFFFFFFFFll},
/* UNDEFINED {"_allshr", &TST_allshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 65, 0xFFFFFFFFFFFFFFFFll}, */
{"_allshr", &TST_allshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 1, 0xFFFFFFFFFFFFFFFFll},
{"_allshr", &TST_allshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 32, 0xFFFFFFFFFFFFFFFFll},
{"_allshr", &TST_allshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 33, 0xFFFFFFFFFFFFFFFFll},
{"_allshr", &TST_allshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 0, 0xFFFFFFFFFFFFFFFFll},
/* UNDEFINED {"_allshr", &TST_allshr, 0x5F5F5F5F5F5F5F5Fll, 0ll, 65, 0x0000000000000000ll}, */
{"_allshr", &TST_allshr, 0x5F5F5F5F5F5F5F5Fll, 0ll, 1, 0x2FAFAFAFAFAFAFAFll},
{"_allshr", &TST_allshr, 0x5F5F5F5F5F5F5F5Fll, 0ll, 32, 0x000000005F5F5F5Fll},
{"_allshr", &TST_allshr, 0x5F5F5F5F5F5F5F5Fll, 0ll, 33, 0x000000002FAFAFAFll},
/* UNDEFINED {"_aullshl", &TST_aullshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 65, 0x0000000000000000ll}, */
{"_aullshl", &TST_aullshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 1, 0xFFFFFFFFFFFFFFFEll},
{"_aullshl", &TST_aullshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 32, 0xFFFFFFFF00000000ll},
{"_aullshl", &TST_aullshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 33, 0xFFFFFFFE00000000ll},
{"_aullshl", &TST_aullshl, 0xFFFFFFFFFFFFFFFFll, 0ll, 0, 0xFFFFFFFFFFFFFFFFll},
/* UNDEFINED {"_aullshr", &TST_aullshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 65, 0x0000000000000000ll}, */
{"_aullshr", &TST_aullshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 1, 0x7FFFFFFFFFFFFFFFll},
{"_aullshr", &TST_aullshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 32, 0x00000000FFFFFFFFll},
{"_aullshr", &TST_aullshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 33, 0x000000007FFFFFFFll},
{"_aullshr", &TST_aullshr, 0xFFFFFFFFFFFFFFFFll, 0ll, 0, 0xFFFFFFFFFFFFFFFFll},
{"_allmul", &TST_allmul, 0xFFFFFFFFFFFFFFFFll, 0x0000000000000000ll, 0, 0x0000000000000000ll},
{"_allmul", &TST_allmul, 0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_allmul", &TST_allmul, 0x000000000FFFFFFFll, 0x0000000000000001ll, 0, 0x000000000FFFFFFFll},
{"_allmul", &TST_allmul, 0x0000000000000001ll, 0x000000000FFFFFFFll, 0, 0x000000000FFFFFFFll},
{"_allmul", &TST_allmul, 0x000000000FFFFFFFll, 0x0000000000000010ll, 0, 0x00000000FFFFFFF0ll},
{"_allmul", &TST_allmul, 0x0000000000000010ll, 0x000000000FFFFFFFll, 0, 0x00000000FFFFFFF0ll},
{"_allmul", &TST_allmul, 0x000000000FFFFFFFll, 0x0000000000000100ll, 0, 0x0000000FFFFFFF00ll},
{"_allmul", &TST_allmul, 0x0000000000000100ll, 0x000000000FFFFFFFll, 0, 0x0000000FFFFFFF00ll},
{"_allmul", &TST_allmul, 0x000000000FFFFFFFll, 0x0000000010000000ll, 0, 0x00FFFFFFF0000000ll},
{"_allmul", &TST_allmul, 0x0000000010000000ll, 0x000000000FFFFFFFll, 0, 0x00FFFFFFF0000000ll},
{"_allmul", &TST_allmul, 0x000000000FFFFFFFll, 0x0000000080000000ll, 0, 0x07FFFFFF80000000ll},
{"_allmul", &TST_allmul, 0x0000000080000000ll, 0x000000000FFFFFFFll, 0, 0x07FFFFFF80000000ll},
{"_allmul", &TST_allmul, 0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll, 0, 0xFFFFFFFF00000000ll},
{"_allmul", &TST_allmul, 0x0000000080000000ll, 0xFFFFFFFFFFFFFFFEll, 0, 0xFFFFFFFF00000000ll},
{"_allmul", &TST_allmul, 0xFFFFFFFFFFFFFFFEll, 0x0000000080000008ll, 0, 0xFFFFFFFEFFFFFFF0ll},
{"_allmul", &TST_allmul, 0x0000000080000008ll, 0xFFFFFFFFFFFFFFFEll, 0, 0xFFFFFFFEFFFFFFF0ll},
{"_allmul", &TST_allmul, 0x00000000FFFFFFFFll, 0x00000000FFFFFFFFll, 0, 0xFFFFFFFE00000001ll},
{"_alldiv", &TST_alldiv, 0x0000000000000000ll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_alldiv", &TST_alldiv, 0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_alldiv", &TST_alldiv, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0xFFFFFFFFFFFFFFFFll},
{"_alldiv", &TST_alldiv, 0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll, 0, 0xFFFFFFFFFFFFFFFFll},
{"_alldiv", &TST_alldiv, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0xFFFFFFFFFFFFFFFFll},
{"_alldiv", &TST_alldiv, 0x0000000000000001ll, 0x0000000000000001ll, 0, 0x0000000000000001ll},
{"_alldiv", &TST_alldiv, 0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000001ll},
{"_alldiv", &TST_alldiv, 0x000000000FFFFFFFll, 0x0000000000000001ll, 0, 0x000000000FFFFFFFll},
{"_alldiv", &TST_alldiv, 0x0000000FFFFFFFFFll, 0x0000000000000010ll, 0, 0x00000000FFFFFFFFll},
{"_alldiv", &TST_alldiv, 0x0000000000000100ll, 0x000000000FFFFFFFll, 0, 0x0000000000000000ll},
{"_alldiv", &TST_alldiv, 0x00FFFFFFF0000000ll, 0x0000000010000000ll, 0, 0x000000000FFFFFFFll},
{"_alldiv", &TST_alldiv, 0x07FFFFFF80000000ll, 0x0000000080000000ll, 0, 0x000000000FFFFFFFll},
{"_alldiv", &TST_alldiv, 0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll, 0, 0x0000000000000000ll},
{"_alldiv", &TST_alldiv, 0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0x0000000080000008ll},
{"_alldiv", &TST_alldiv, 0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0xC000000080000008ll},
{"_alldiv", &TST_alldiv, 0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll, 0, 0x0000000000007FFFll},
{"_alldiv", &TST_alldiv, 0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll, 0, 0x0000000000000001ll},
{"_allrem", &TST_allrem, 0x0000000000000000ll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x0000000000000001ll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x000000000FFFFFFFll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x0000000FFFFFFFFFll, 0x0000000000000010ll, 0, 0x000000000000000Fll},
{"_allrem", &TST_allrem, 0x0000000000000100ll, 0x000000000FFFFFFFll, 0, 0x0000000000000100ll},
{"_allrem", &TST_allrem, 0x00FFFFFFF0000000ll, 0x0000000010000000ll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x07FFFFFF80000000ll, 0x0000000080000000ll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll, 0, 0xFFFFFFFFFFFFFFFEll},
{"_allrem", &TST_allrem, 0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0x0000000000000000ll},
{"_allrem", &TST_allrem, 0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll, 0, 0x0000FFFF0000FFEEll},
{"_allrem", &TST_allrem, 0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x0000000000000000ll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll, 0, 0xFFFFFFFFFFFFFFFFll},
{"_ualldiv", &TST_ualldiv, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x0000000000000001ll, 0x0000000000000001ll, 0, 0x0000000000000001ll},
{"_ualldiv", &TST_ualldiv, 0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000001ll},
{"_ualldiv", &TST_ualldiv, 0x000000000FFFFFFFll, 0x0000000000000001ll, 0, 0x000000000FFFFFFFll},
{"_ualldiv", &TST_ualldiv, 0x0000000FFFFFFFFFll, 0x0000000000000010ll, 0, 0x00000000FFFFFFFFll},
{"_ualldiv", &TST_ualldiv, 0x0000000000000100ll, 0x000000000FFFFFFFll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x00FFFFFFF0000000ll, 0x0000000010000000ll, 0, 0x000000000FFFFFFFll},
{"_ualldiv", &TST_ualldiv, 0x07FFFFFF80000000ll, 0x0000000080000000ll, 0, 0x000000000FFFFFFFll},
{"_ualldiv", &TST_ualldiv, 0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll, 0, 0x00000001FFFFFFFFll},
{"_ualldiv", &TST_ualldiv, 0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0x0000000000000000ll},
{"_ualldiv", &TST_ualldiv, 0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll, 0, 0x0000000000007FFFll},
{"_ualldiv", &TST_ualldiv, 0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll, 0, 0x0000000000000001ll},
{"_uallrem", &TST_uallrem, 0x0000000000000000ll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0x0000000000000000ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000001ll},
{"_uallrem", &TST_uallrem, 0xFFFFFFFFFFFFFFFFll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0x0000000000000001ll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000001ll},
{"_uallrem", &TST_uallrem, 0x0000000000000001ll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0xFFFFFFFFFFFFFFFFll, 0xFFFFFFFFFFFFFFFFll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0x000000000FFFFFFFll, 0x0000000000000001ll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0x0000000FFFFFFFFFll, 0x0000000000000010ll, 0, 0x000000000000000Fll},
{"_uallrem", &TST_uallrem, 0x0000000000000100ll, 0x000000000FFFFFFFll, 0, 0x0000000000000100ll},
{"_uallrem", &TST_uallrem, 0x00FFFFFFF0000000ll, 0x0000000010000000ll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0x07FFFFFF80000000ll, 0x0000000080000000ll, 0, 0x0000000000000000ll},
{"_uallrem", &TST_uallrem, 0xFFFFFFFFFFFFFFFEll, 0x0000000080000000ll, 0, 0x000000007FFFFFFEll},
{"_uallrem", &TST_uallrem, 0xFFFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0xFFFFFFFEFFFFFFF0ll},
{"_uallrem", &TST_uallrem, 0x7FFFFFFEFFFFFFF0ll, 0xFFFFFFFFFFFFFFFEll, 0, 0x7FFFFFFEFFFFFFF0ll},
{"_uallrem", &TST_uallrem, 0x7FFFFFFEFFFFFFF0ll, 0x0000FFFFFFFFFFFEll, 0, 0x0000FFFF0000FFEEll},
{"_uallrem", &TST_uallrem, 0x7FFFFFFEFFFFFFF0ll, 0x7FFFFFFEFFFFFFF0ll, 0, 0x0000000000000000ll},
{NULL}
};
int
Test64Bit (SDL_bool verbose)
{
LL_Test *t;
int failed = 0;
for (t = LL_Tests; t->routine != NULL; t++) {
unsigned long long result = 0;
unsigned int *al = (unsigned int *)&t->a;
unsigned int *bl = (unsigned int *)&t->b;
unsigned int *el = (unsigned int *)&t->expected_result;
unsigned int *rl = (unsigned int *)&result;
if (!t->routine(&t->a, &t->b, t->arg, &result, &t->expected_result)) {
if (verbose)
SDL_Log("%s(0x%08X%08X, 0x%08X%08X, %3d, produced: 0x%08X%08X, expected: 0x%08X%08X\n",
t->operation, al[1], al[0], bl[1], bl[0], t->arg, rl[1], rl[0], el[1], el[0]);
++failed;
}
}
if (verbose && (failed == 0))
SDL_Log("All 64bit instrinsic tests passed\n");
return (failed ? 1 : 0);
}
int
TestCPUInfo(SDL_bool verbose)
{
if (verbose) {
SDL_Log("CPU count: %d\n", SDL_GetCPUCount());
SDL_Log("CPU cache line size: %d\n", SDL_GetCPUCacheLineSize());
SDL_Log("RDTSC %s\n", SDL_HasRDTSC()? "detected" : "not detected");
SDL_Log("AltiVec %s\n", SDL_HasAltiVec()? "detected" : "not detected");
SDL_Log("MMX %s\n", SDL_HasMMX()? "detected" : "not detected");
SDL_Log("3DNow! %s\n", SDL_Has3DNow()? "detected" : "not detected");
SDL_Log("SSE %s\n", SDL_HasSSE()? "detected" : "not detected");
SDL_Log("SSE2 %s\n", SDL_HasSSE2()? "detected" : "not detected");
SDL_Log("SSE3 %s\n", SDL_HasSSE3()? "detected" : "not detected");
SDL_Log("SSE4.1 %s\n", SDL_HasSSE41()? "detected" : "not detected");
SDL_Log("SSE4.2 %s\n", SDL_HasSSE42()? "detected" : "not detected");
SDL_Log("AVX %s\n", SDL_HasAVX()? "detected" : "not detected");
SDL_Log("AVX2 %s\n", SDL_HasAVX2()? "detected" : "not detected");
SDL_Log("AVX-512F %s\n", SDL_HasAVX512F()? "detected" : "not detected");
SDL_Log("NEON %s\n", SDL_HasNEON()? "detected" : "not detected");
SDL_Log("System RAM %d MB\n", SDL_GetSystemRAM());
}
return (0);
}
int
TestAssertions(SDL_bool verbose)
{
SDL_assert(1);
SDL_assert_release(1);
SDL_assert_paranoid(1);
SDL_assert(0 || 1);
SDL_assert_release(0 || 1);
SDL_assert_paranoid(0 || 1);
#if 0 /* enable this to test assertion failures. */
SDL_assert_release(1 == 2);
SDL_assert_release(5 < 4);
SDL_assert_release(0 && "This is a test");
#endif
{
const SDL_AssertData *item = SDL_GetAssertionReport();
while (item) {
SDL_Log("'%s', %s (%s:%d), triggered %u times, always ignore: %s.\n",
item->condition, item->function, item->filename,
item->linenum, item->trigger_count,
item->always_ignore ? "yes" : "no");
item = item->next;
}
}
return (0);
}
int
main(int argc, char *argv[])
{
SDL_bool verbose = SDL_TRUE;
int status = 0;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (argv[1] && (SDL_strcmp(argv[1], "-q") == 0)) {
verbose = SDL_FALSE;
}
if (verbose) {
SDL_Log("This system is running %s\n", SDL_GetPlatform());
}
status += TestTypes(verbose);
status += TestEndian(verbose);
status += Test64Bit(verbose);
status += TestCPUInfo(verbose);
status += TestAssertions(verbose);
return status;
}
| YifuLiu/AliOS-Things | components/SDL2/test/testplatform.c | C | apache-2.0 | 22,149 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of power subsystem. */
#include <stdio.h>
#include "SDL.h"
static void
report_power(void)
{
int seconds, percent;
const SDL_PowerState state = SDL_GetPowerInfo(&seconds, &percent);
char *statestr = NULL;
SDL_Log("SDL-reported power info...\n");
switch (state) {
case SDL_POWERSTATE_UNKNOWN:
statestr = "Unknown";
break;
case SDL_POWERSTATE_ON_BATTERY:
statestr = "On battery";
break;
case SDL_POWERSTATE_NO_BATTERY:
statestr = "No battery";
break;
case SDL_POWERSTATE_CHARGING:
statestr = "Charging";
break;
case SDL_POWERSTATE_CHARGED:
statestr = "Charged";
break;
default:
statestr = "!!API ERROR!!";
break;
}
SDL_Log("State: %s\n", statestr);
if (percent == -1) {
SDL_Log("Percent left: unknown\n");
} else {
SDL_Log("Percent left: %d%%\n", percent);
}
if (seconds == -1) {
SDL_Log("Time left: unknown\n");
} else {
SDL_Log("Time left: %d minutes, %d seconds\n", (int) (seconds / 60),
(int) (seconds % 60));
}
}
int
main(int argc, char *argv[])
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_Init(0) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError());
return 1;
}
report_power();
SDL_Quit();
return 0;
}
/* end of testpower.c ... */
| YifuLiu/AliOS-Things | components/SDL2/test/testpower.c | C | apache-2.0 | 1,953 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "SDL_test.h"
static int
num_compare(const void *_a, const void *_b)
{
const int a = *((const int *) _a);
const int b = *((const int *) _b);
return (a < b) ? -1 : ((a > b) ? 1 : 0);
}
static void
test_sort(const char *desc, int *nums, const int arraylen)
{
int i;
int prev;
SDL_Log("test: %s arraylen=%d", desc, arraylen);
SDL_qsort(nums, arraylen, sizeof (nums[0]), num_compare);
prev = nums[0];
for (i = 1; i < arraylen; i++) {
const int val = nums[i];
if (val < prev) {
SDL_Log("sort is broken!");
return;
}
prev = val;
}
}
int
main(int argc, char *argv[])
{
static int nums[1024 * 100];
static const int itervals[] = { SDL_arraysize(nums), 12 };
int iteration;
SDLTest_RandomContext rndctx;
if (argc > 1)
{
int success;
Uint64 seed = 0;
if (argv[1][0] == '0' && argv[1][1] == 'x')
success = SDL_sscanf(argv[1] + 2, "%llx", &seed);
else
success = SDL_sscanf(argv[1], "%llu", &seed);
if (!success) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Invalid seed. Use a decimal or hexadecimal number.\n");
return 1;
}
if (seed <= ((Uint64)0xffffffff)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Seed must be equal or greater than 0x100000000.\n");
return 1;
}
SDLTest_RandomInit(&rndctx, (unsigned int)(seed >> 32), (unsigned int)(seed & 0xffffffff));
}
else
{
SDLTest_RandomInitTime(&rndctx);
}
SDL_Log("Using random seed 0x%08x%08x\n", rndctx.x, rndctx.c);
for (iteration = 0; iteration < SDL_arraysize(itervals); iteration++) {
const int arraylen = itervals[iteration];
int i;
for (i = 0; i < arraylen; i++) {
nums[i] = i;
}
test_sort("already sorted", nums, arraylen);
for (i = 0; i < arraylen; i++) {
nums[i] = i;
}
nums[arraylen-1] = -1;
test_sort("already sorted except last element", nums, arraylen);
for (i = 0; i < arraylen; i++) {
nums[i] = (arraylen-1) - i;
}
test_sort("reverse sorted", nums, arraylen);
for (i = 0; i < arraylen; i++) {
nums[i] = SDLTest_RandomInt(&rndctx);
}
test_sort("random sorted", nums, arraylen);
}
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testqsort.c | C | apache-2.0 | 2,883 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Test relative mouse motion */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include "SDL_test_common.h"
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
static SDLTest_CommonState *state;
int i, done;
SDL_Rect rect;
SDL_Event event;
static void
DrawRects(SDL_Renderer * renderer, SDL_Rect * rect)
{
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderFillRect(renderer, rect);
}
static void
loop(){
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
switch(event.type) {
case SDL_MOUSEMOTION:
{
rect.x += event.motion.xrel;
rect.y += event.motion.yrel;
}
break;
}
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Rect viewport;
SDL_Renderer *renderer = state->renderers[i];
if (state->windows[i] == NULL)
continue;
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xFF);
SDL_RenderClear(renderer);
/* Wrap the cursor rectangle at the screen edges to keep it visible */
SDL_RenderGetViewport(renderer, &viewport);
if (rect.x < viewport.x) rect.x += viewport.w;
if (rect.y < viewport.y) rect.y += viewport.h;
if (rect.x > viewport.x + viewport.w) rect.x -= viewport.w;
if (rect.y > viewport.y + viewport.h) rect.y -= viewport.h;
DrawRects(renderer, &rect);
SDL_RenderPresent(renderer);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc; ++i) {
SDLTest_CommonArg(state, i);
}
if (!SDLTest_CommonInit(state)) {
return 2;
}
/* Create the windows and initialize the renderers */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
srand((unsigned int)time(NULL));
if(SDL_SetRelativeMouseMode(SDL_TRUE) < 0) {
return 3;
};
rect.x = DEFAULT_WINDOW_WIDTH / 2;
rect.y = DEFAULT_WINDOW_HEIGHT / 2;
rect.w = 10;
rect.h = 10;
/* Main render loop */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDLTest_CommonQuit(state);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testrelative.c | C | apache-2.0 | 3,285 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
static SDLTest_CommonState *state;
typedef struct {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *background;
SDL_Texture *sprite;
SDL_Rect sprite_rect;
int scale_direction;
} DrawState;
DrawState *drawstates;
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
SDL_Texture *
LoadTexture(SDL_Renderer *renderer, const char *file, SDL_bool transparent)
{
SDL_Surface *temp;
SDL_Texture *texture;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return NULL;
}
/* Set transparent pixel as the pixel at (0,0) */
if (transparent) {
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
}
/* Create textures from the image */
texture = SDL_CreateTextureFromSurface(renderer, temp);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return NULL;
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return texture;
}
void
Draw(DrawState *s)
{
SDL_Rect viewport;
SDL_Texture *target;
SDL_Point *center=NULL;
SDL_Point origin = {0,0};
SDL_RenderGetViewport(s->renderer, &viewport);
target = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, viewport.w, viewport.h);
SDL_SetRenderTarget(s->renderer, target);
/* Draw the background */
SDL_RenderCopy(s->renderer, s->background, NULL, NULL);
/* Scale and draw the sprite */
s->sprite_rect.w += s->scale_direction;
s->sprite_rect.h += s->scale_direction;
if (s->scale_direction > 0) {
center = &origin;
if (s->sprite_rect.w >= viewport.w || s->sprite_rect.h >= viewport.h) {
s->scale_direction = -1;
}
} else {
if (s->sprite_rect.w <= 1 || s->sprite_rect.h <= 1) {
s->scale_direction = 1;
}
}
s->sprite_rect.x = (viewport.w - s->sprite_rect.w) / 2;
s->sprite_rect.y = (viewport.h - s->sprite_rect.h) / 2;
SDL_RenderCopyEx(s->renderer, s->sprite, NULL, &s->sprite_rect, (double)s->sprite_rect.w, center, (SDL_RendererFlip)s->scale_direction);
SDL_SetRenderTarget(s->renderer, NULL);
SDL_RenderCopy(s->renderer, target, NULL, NULL);
SDL_DestroyTexture(target);
/* Update the screen! */
SDL_RenderPresent(s->renderer);
/* SDL_Delay(10); */
}
void loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
Draw(&drawstates[i]);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
int frames;
Uint32 then, now;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
if (!SDLTest_CommonDefaultArgs(state, argc, argv) || !SDLTest_CommonInit(state)) {
SDLTest_CommonQuit(state);
return 1;
}
drawstates = SDL_stack_alloc(DrawState, state->num_windows);
for (i = 0; i < state->num_windows; ++i) {
DrawState *drawstate = &drawstates[i];
drawstate->window = state->windows[i];
drawstate->renderer = state->renderers[i];
drawstate->sprite = LoadTexture(drawstate->renderer, "icon.bmp", SDL_TRUE);
drawstate->background = LoadTexture(drawstate->renderer, "sample.bmp", SDL_FALSE);
if (!drawstate->sprite || !drawstate->background) {
quit(2);
}
SDL_QueryTexture(drawstate->sprite, NULL, NULL,
&drawstate->sprite_rect.w, &drawstate->sprite_rect.h);
drawstate->scale_direction = 1;
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
}
#endif
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
SDL_stack_free(drawstates);
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testrendercopyex.c | C | apache-2.0 | 6,132 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
static SDLTest_CommonState *state;
typedef struct {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *background;
SDL_Texture *sprite;
SDL_Rect sprite_rect;
int scale_direction;
} DrawState;
DrawState *drawstates;
int done;
SDL_bool test_composite = SDL_FALSE;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
SDL_Texture *
LoadTexture(SDL_Renderer *renderer, char *file, SDL_bool transparent)
{
SDL_Surface *temp;
SDL_Texture *texture;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return NULL;
}
/* Set transparent pixel as the pixel at (0,0) */
if (transparent) {
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
}
/* Create textures from the image */
texture = SDL_CreateTextureFromSurface(renderer, temp);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return NULL;
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return texture;
}
SDL_bool
DrawComposite(DrawState *s)
{
SDL_Rect viewport, R;
SDL_Texture *target;
static SDL_bool blend_tested = SDL_FALSE;
if (!blend_tested) {
SDL_Texture *A, *B;
Uint32 P;
A = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1, 1);
SDL_SetTextureBlendMode(A, SDL_BLENDMODE_BLEND);
B = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, 1, 1);
SDL_SetTextureBlendMode(B, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(s->renderer, A);
SDL_SetRenderDrawColor(s->renderer, 0x00, 0x00, 0x00, 0x80);
SDL_RenderFillRect(s->renderer, NULL);
SDL_SetRenderTarget(s->renderer, B);
SDL_SetRenderDrawColor(s->renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderFillRect(s->renderer, NULL);
SDL_RenderCopy(s->renderer, A, NULL, NULL);
SDL_RenderReadPixels(s->renderer, NULL, SDL_PIXELFORMAT_ARGB8888, &P, sizeof(P));
SDL_Log("Blended pixel: 0x%8.8X\n", P);
SDL_DestroyTexture(A);
SDL_DestroyTexture(B);
blend_tested = SDL_TRUE;
}
SDL_RenderGetViewport(s->renderer, &viewport);
target = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, viewport.w, viewport.h);
SDL_SetTextureBlendMode(target, SDL_BLENDMODE_BLEND);
SDL_SetRenderTarget(s->renderer, target);
/* Draw the background.
This is solid black so when the sprite is copied to it, any per-pixel alpha will be blended through.
*/
SDL_SetRenderDrawColor(s->renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderFillRect(s->renderer, NULL);
/* Scale and draw the sprite */
s->sprite_rect.w += s->scale_direction;
s->sprite_rect.h += s->scale_direction;
if (s->scale_direction > 0) {
if (s->sprite_rect.w >= viewport.w || s->sprite_rect.h >= viewport.h) {
s->scale_direction = -1;
}
} else {
if (s->sprite_rect.w <= 1 || s->sprite_rect.h <= 1) {
s->scale_direction = 1;
}
}
s->sprite_rect.x = (viewport.w - s->sprite_rect.w) / 2;
s->sprite_rect.y = (viewport.h - s->sprite_rect.h) / 2;
SDL_RenderCopy(s->renderer, s->sprite, NULL, &s->sprite_rect);
SDL_SetRenderTarget(s->renderer, NULL);
SDL_RenderCopy(s->renderer, s->background, NULL, NULL);
SDL_SetRenderDrawBlendMode(s->renderer, SDL_BLENDMODE_BLEND);
SDL_SetRenderDrawColor(s->renderer, 0xff, 0x00, 0x00, 0x80);
R.x = 0;
R.y = 0;
R.w = 100;
R.h = 100;
SDL_RenderFillRect(s->renderer, &R);
SDL_SetRenderDrawBlendMode(s->renderer, SDL_BLENDMODE_NONE);
SDL_RenderCopy(s->renderer, target, NULL, NULL);
SDL_DestroyTexture(target);
/* Update the screen! */
SDL_RenderPresent(s->renderer);
return SDL_TRUE;
}
SDL_bool
Draw(DrawState *s)
{
SDL_Rect viewport;
SDL_Texture *target;
SDL_RenderGetViewport(s->renderer, &viewport);
target = SDL_CreateTexture(s->renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_TARGET, viewport.w, viewport.h);
if (!target) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create render target texture: %s\n", SDL_GetError());
return SDL_FALSE;
}
SDL_SetRenderTarget(s->renderer, target);
/* Draw the background */
SDL_RenderCopy(s->renderer, s->background, NULL, NULL);
/* Scale and draw the sprite */
s->sprite_rect.w += s->scale_direction;
s->sprite_rect.h += s->scale_direction;
if (s->scale_direction > 0) {
if (s->sprite_rect.w >= viewport.w || s->sprite_rect.h >= viewport.h) {
s->scale_direction = -1;
}
} else {
if (s->sprite_rect.w <= 1 || s->sprite_rect.h <= 1) {
s->scale_direction = 1;
}
}
s->sprite_rect.x = (viewport.w - s->sprite_rect.w) / 2;
s->sprite_rect.y = (viewport.h - s->sprite_rect.h) / 2;
SDL_RenderCopy(s->renderer, s->sprite, NULL, &s->sprite_rect);
SDL_SetRenderTarget(s->renderer, NULL);
SDL_RenderCopy(s->renderer, target, NULL, NULL);
SDL_DestroyTexture(target);
/* Update the screen! */
SDL_RenderPresent(s->renderer);
return SDL_TRUE;
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
if (test_composite) {
if (!DrawComposite(&drawstates[i])) done = 1;
} else {
if (!Draw(&drawstates[i])) done = 1;
}
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
int frames;
Uint32 then, now;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--composite") == 0) {
test_composite = SDL_TRUE;
consumed = 1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--composite]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
drawstates = SDL_stack_alloc(DrawState, state->num_windows);
for (i = 0; i < state->num_windows; ++i) {
DrawState *drawstate = &drawstates[i];
drawstate->window = state->windows[i];
drawstate->renderer = state->renderers[i];
if (test_composite) {
drawstate->sprite = LoadTexture(drawstate->renderer, "icon-alpha.bmp", SDL_TRUE);
} else {
drawstate->sprite = LoadTexture(drawstate->renderer, "icon.bmp", SDL_TRUE);
}
drawstate->background = LoadTexture(drawstate->renderer, "sample.bmp", SDL_FALSE);
if (!drawstate->sprite || !drawstate->background) {
quit(2);
}
SDL_QueryTexture(drawstate->sprite, NULL, NULL,
&drawstate->sprite_rect.w, &drawstate->sprite_rect.h);
drawstate->scale_direction = 1;
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
}
#endif
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
SDL_stack_free(drawstates);
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testrendertarget.c | C | apache-2.0 | 9,757 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "SDL.h"
int
main(int argc, char **argv)
{
SDL_AudioSpec spec;
SDL_AudioCVT cvt;
Uint32 len = 0;
Uint8 *data = NULL;
int cvtfreq = 0;
int cvtchans = 0;
int bitsize = 0;
int blockalign = 0;
int avgbytes = 0;
SDL_RWops *io = NULL;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (argc != 5) {
SDL_Log("USAGE: %s in.wav out.wav newfreq newchans\n", argv[0]);
return 1;
}
cvtfreq = SDL_atoi(argv[3]);
cvtchans = SDL_atoi(argv[4]);
if (SDL_Init(SDL_INIT_AUDIO) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init() failed: %s\n", SDL_GetError());
return 2;
}
if (SDL_LoadWAV(argv[1], &spec, &data, &len) == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "failed to load %s: %s\n", argv[1], SDL_GetError());
SDL_Quit();
return 3;
}
if (SDL_BuildAudioCVT(&cvt, spec.format, spec.channels, spec.freq,
spec.format, cvtchans, cvtfreq) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "failed to build CVT: %s\n", SDL_GetError());
SDL_FreeWAV(data);
SDL_Quit();
return 4;
}
cvt.len = len;
cvt.buf = (Uint8 *) SDL_malloc(len * cvt.len_mult);
if (cvt.buf == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory.\n");
SDL_FreeWAV(data);
SDL_Quit();
return 5;
}
SDL_memcpy(cvt.buf, data, len);
if (SDL_ConvertAudio(&cvt) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Conversion failed: %s\n", SDL_GetError());
SDL_free(cvt.buf);
SDL_FreeWAV(data);
SDL_Quit();
return 6;
}
/* write out a WAV header... */
io = SDL_RWFromFile(argv[2], "wb");
if (io == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "fopen('%s') failed: %s\n", argv[2], SDL_GetError());
SDL_free(cvt.buf);
SDL_FreeWAV(data);
SDL_Quit();
return 7;
}
bitsize = SDL_AUDIO_BITSIZE(spec.format);
blockalign = (bitsize / 8) * cvtchans;
avgbytes = cvtfreq * blockalign;
SDL_WriteLE32(io, 0x46464952); /* RIFF */
SDL_WriteLE32(io, cvt.len_cvt + 36);
SDL_WriteLE32(io, 0x45564157); /* WAVE */
SDL_WriteLE32(io, 0x20746D66); /* fmt */
SDL_WriteLE32(io, 16); /* chunk size */
SDL_WriteLE16(io, SDL_AUDIO_ISFLOAT(spec.format) ? 3 : 1); /* uncompressed */
SDL_WriteLE16(io, cvtchans); /* channels */
SDL_WriteLE32(io, cvtfreq); /* sample rate */
SDL_WriteLE32(io, avgbytes); /* average bytes per second */
SDL_WriteLE16(io, blockalign); /* block align */
SDL_WriteLE16(io, bitsize); /* significant bits per sample */
SDL_WriteLE32(io, 0x61746164); /* data */
SDL_WriteLE32(io, cvt.len_cvt); /* size */
SDL_RWwrite(io, cvt.buf, cvt.len_cvt, 1);
if (SDL_RWclose(io) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "fclose('%s') failed: %s\n", argv[2], SDL_GetError());
SDL_free(cvt.buf);
SDL_FreeWAV(data);
SDL_Quit();
return 8;
} /* if */
SDL_free(cvt.buf);
SDL_FreeWAV(data);
SDL_Quit();
return 0;
} /* main */
/* end of testresample.c ... */
| YifuLiu/AliOS-Things | components/SDL2/test/testresample.c | C | apache-2.0 | 3,818 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/*
Copyright (c) 2011, Edgar Simo Serra
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Simple Directmedia Layer (SDL) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* includes
*/
#include <stdlib.h>
#include <string.h> /* strstr */
#include <ctype.h> /* isdigit */
#include "SDL.h"
#ifndef SDL_HAPTIC_DISABLED
static SDL_Haptic *haptic;
/**
* @brief The entry point of this force feedback demo.
* @param[in] argc Number of arguments.
* @param[in] argv Array of argc arguments.
*/
int
main(int argc, char **argv)
{
int i;
char *name;
int index;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
name = NULL;
index = -1;
if (argc > 1) {
size_t l;
name = argv[1];
if ((strcmp(name, "--help") == 0) || (strcmp(name, "-h") == 0)) {
SDL_Log("USAGE: %s [device]\n"
"If device is a two-digit number it'll use it as an index, otherwise\n"
"it'll use it as if it were part of the device's name.\n",
argv[0]);
return 0;
}
l = SDL_strlen(name);
if ((l < 3) && SDL_isdigit(name[0]) && ((l == 1) || SDL_isdigit(name[1]))) {
index = SDL_atoi(name);
name = NULL;
}
}
/* Initialize the force feedbackness */
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_JOYSTICK |
SDL_INIT_HAPTIC);
SDL_Log("%d Haptic devices detected.\n", SDL_NumHaptics());
if (SDL_NumHaptics() > 0) {
/* We'll just use index or the first force feedback device found */
if (name == NULL) {
i = (index != -1) ? index : 0;
}
/* Try to find matching device */
else {
for (i = 0; i < SDL_NumHaptics(); i++) {
if (strstr(SDL_HapticName(i), name) != NULL)
break;
}
if (i >= SDL_NumHaptics()) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to find device matching '%s', aborting.\n",
name);
return 1;
}
}
haptic = SDL_HapticOpen(i);
if (haptic == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create the haptic device: %s\n",
SDL_GetError());
return 1;
}
SDL_Log("Device: %s\n", SDL_HapticName(i));
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Haptic devices found!\n");
return 1;
}
/* We only want force feedback errors. */
SDL_ClearError();
if (SDL_HapticRumbleSupported(haptic) == SDL_FALSE) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Rumble not supported!\n");
return 1;
}
if (SDL_HapticRumbleInit(haptic) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialize rumble: %s\n", SDL_GetError());
return 1;
}
SDL_Log("Playing 2 second rumble at 0.5 magnitude.\n");
if (SDL_HapticRumblePlay(haptic, 0.5, 5000) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() );
return 1;
}
SDL_Delay(2000);
SDL_Log("Stopping rumble.\n");
SDL_HapticRumbleStop(haptic);
SDL_Delay(2000);
SDL_Log("Playing 2 second rumble at 0.3 magnitude.\n");
if (SDL_HapticRumblePlay(haptic, 0.3f, 5000) != 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to play rumble: %s\n", SDL_GetError() );
return 1;
}
SDL_Delay(2000);
/* Quit */
if (haptic != NULL)
SDL_HapticClose(haptic);
SDL_Quit();
return 0;
}
#else
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Haptic support.\n");
return 1;
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testrumble.c | C | apache-2.0 | 5,632 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
static SDLTest_CommonState *state;
typedef struct {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *background;
SDL_Texture *sprite;
SDL_Rect sprite_rect;
int scale_direction;
} DrawState;
DrawState *drawstates;
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
SDL_Texture *
LoadTexture(SDL_Renderer *renderer, char *file, SDL_bool transparent)
{
SDL_Surface *temp;
SDL_Texture *texture;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return NULL;
}
/* Set transparent pixel as the pixel at (0,0) */
if (transparent) {
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
}
/* Create textures from the image */
texture = SDL_CreateTextureFromSurface(renderer, temp);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return NULL;
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return texture;
}
void
Draw(DrawState *s)
{
SDL_Rect viewport;
SDL_RenderGetViewport(s->renderer, &viewport);
/* Draw the background */
SDL_RenderCopy(s->renderer, s->background, NULL, NULL);
/* Scale and draw the sprite */
s->sprite_rect.w += s->scale_direction;
s->sprite_rect.h += s->scale_direction;
if (s->scale_direction > 0) {
if (s->sprite_rect.w >= viewport.w || s->sprite_rect.h >= viewport.h) {
s->scale_direction = -1;
}
} else {
if (s->sprite_rect.w <= 1 || s->sprite_rect.h <= 1) {
s->scale_direction = 1;
}
}
s->sprite_rect.x = (viewport.w - s->sprite_rect.w) / 2;
s->sprite_rect.y = (viewport.h - s->sprite_rect.h) / 2;
SDL_RenderCopy(s->renderer, s->sprite, NULL, &s->sprite_rect);
/* Update the screen! */
SDL_RenderPresent(s->renderer);
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
Draw(&drawstates[i]);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
int frames;
Uint32 then, now;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
if (!SDLTest_CommonDefaultArgs(state, argc, argv) || !SDLTest_CommonInit(state)) {
SDLTest_CommonQuit(state);
return 1;
}
drawstates = SDL_stack_alloc(DrawState, state->num_windows);
for (i = 0; i < state->num_windows; ++i) {
DrawState *drawstate = &drawstates[i];
drawstate->window = state->windows[i];
drawstate->renderer = state->renderers[i];
drawstate->sprite = LoadTexture(drawstate->renderer, "icon.bmp", SDL_TRUE);
drawstate->background = LoadTexture(drawstate->renderer, "sample.bmp", SDL_FALSE);
if (!drawstate->sprite || !drawstate->background) {
quit(2);
}
SDL_QueryTexture(drawstate->sprite, NULL, NULL,
&drawstate->sprite_rect.w, &drawstate->sprite_rect.h);
drawstate->scale_direction = 1;
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
}
#endif
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
SDL_stack_free(drawstates);
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testscale.c | C | apache-2.0 | 5,672 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL semaphore code */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "SDL.h"
#define NUM_THREADS 10
static SDL_sem *sem;
int alive = 1;
int SDLCALL
ThreadFunc(void *data)
{
int threadnum = (int) (uintptr_t) data;
while (alive) {
SDL_SemWait(sem);
SDL_Log("Thread number %d has got the semaphore (value = %d)!\n",
threadnum, SDL_SemValue(sem));
SDL_Delay(200);
SDL_SemPost(sem);
SDL_Log("Thread number %d has released the semaphore (value = %d)!\n",
threadnum, SDL_SemValue(sem));
SDL_Delay(1); /* For the scheduler */
}
SDL_Log("Thread number %d exiting.\n", threadnum);
return 0;
}
static void
killed(int sig)
{
alive = 0;
}
static void
TestWaitTimeout(void)
{
Uint32 start_ticks;
Uint32 end_ticks;
Uint32 duration;
int retval;
sem = SDL_CreateSemaphore(0);
SDL_Log("Waiting 2 seconds on semaphore\n");
start_ticks = SDL_GetTicks();
retval = SDL_SemWaitTimeout(sem, 2000);
end_ticks = SDL_GetTicks();
duration = end_ticks - start_ticks;
/* Accept a little offset in the effective wait */
if (duration > 1900 && duration < 2050)
SDL_Log("Wait done.\n");
else
SDL_Log("Wait took %d milliseconds\n", duration);
/* Check to make sure the return value indicates timed out */
if (retval != SDL_MUTEX_TIMEDOUT)
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_SemWaitTimeout returned: %d; expected: %d\n", retval, SDL_MUTEX_TIMEDOUT);
}
int
main(int argc, char **argv)
{
SDL_Thread *threads[NUM_THREADS];
uintptr_t i;
int init_sem;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (argc < 2) {
SDL_Log("Usage: %s init_value\n", argv[0]);
return (1);
}
/* Load the SDL library */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
signal(SIGTERM, killed);
signal(SIGINT, killed);
init_sem = atoi(argv[1]);
sem = SDL_CreateSemaphore(init_sem);
SDL_Log("Running %d threads, semaphore value = %d\n", NUM_THREADS,
init_sem);
/* Create all the threads */
for (i = 0; i < NUM_THREADS; ++i) {
char name[64];
SDL_snprintf(name, sizeof (name), "Thread%u", (unsigned int) i);
threads[i] = SDL_CreateThread(ThreadFunc, name, (void *) i);
}
/* Wait 10 seconds */
SDL_Delay(10 * 1000);
/* Wait for all threads to finish */
SDL_Log("Waiting for threads to finish\n");
alive = 0;
for (i = 0; i < NUM_THREADS; ++i) {
SDL_WaitThread(threads[i], NULL);
}
SDL_Log("Finished waiting for threads\n");
SDL_DestroySemaphore(sem);
TestWaitTimeout();
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testsem.c | C | apache-2.0 | 3,357 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL sensor code */
#include "SDL.h"
static const char *GetSensorTypeString(SDL_SensorType type)
{
static char unknown_type[64];
switch (type)
{
case SDL_SENSOR_INVALID:
return "SDL_SENSOR_INVALID";
case SDL_SENSOR_UNKNOWN:
return "SDL_SENSOR_UNKNOWN";
case SDL_SENSOR_ACCEL:
return "SDL_SENSOR_ACCEL";
case SDL_SENSOR_GYRO:
return "SDL_SENSOR_GYRO";
default:
SDL_snprintf(unknown_type, sizeof(unknown_type), "UNKNOWN (%d)", type);
return unknown_type;
}
}
static void HandleSensorEvent(SDL_SensorEvent *event)
{
SDL_Sensor *sensor = SDL_SensorFromInstanceID(event->which);
if (!sensor) {
SDL_Log("Couldn't get sensor for sensor event\n");
return;
}
switch (SDL_SensorGetType(sensor)) {
case SDL_SENSOR_ACCEL:
SDL_Log("Accelerometer update: %.2f, %.2f, %.2f\n", event->data[0], event->data[1], event->data[2]);
break;
case SDL_SENSOR_GYRO:
SDL_Log("Gyro update: %.2f, %.2f, %.2f\n", event->data[0], event->data[1], event->data[2]);
break;
default:
SDL_Log("Sensor update for sensor type %s\n", GetSensorTypeString(SDL_SensorGetType(sensor)));
break;
}
}
int
main(int argc, char **argv)
{
int i;
int num_sensors, num_opened;
/* Load the SDL library */
if (SDL_Init(SDL_INIT_SENSOR) < 0) {
SDL_Log("Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
num_sensors = SDL_NumSensors();
num_opened = 0;
SDL_Log("There are %d sensors available\n", num_sensors);
for (i = 0; i < num_sensors; ++i) {
SDL_Log("Sensor %d: %s, type %s, platform type %d\n",
SDL_SensorGetDeviceInstanceID(i),
SDL_SensorGetDeviceName(i),
GetSensorTypeString(SDL_SensorGetDeviceType(i)),
SDL_SensorGetDeviceNonPortableType(i));
if (SDL_SensorGetDeviceType(i) != SDL_SENSOR_UNKNOWN) {
SDL_Sensor *sensor = SDL_SensorOpen(i);
if (sensor == NULL) {
SDL_Log("Couldn't open sensor %d: %s\n", SDL_SensorGetDeviceInstanceID(i), SDL_GetError());
} else {
++num_opened;
}
}
}
SDL_Log("Opened %d sensors\n", num_opened);
if (num_opened > 0) {
SDL_bool done = SDL_FALSE;
SDL_Event event;
SDL_CreateWindow("Sensor Test", 0, 0, 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
while (!done) {
while (SDL_PollEvent(&event) > 0) {
switch (event.type) {
case SDL_SENSORUPDATE:
HandleSensorEvent(&event.sensor);
break;
case SDL_MOUSEBUTTONUP:
case SDL_KEYUP:
case SDL_QUIT:
done = SDL_TRUE;
break;
default:
break;
}
}
}
}
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testsensor.c | C | apache-2.0 | 3,423 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* This is a simple example of using GLSL shaders with SDL */
#include "SDL.h"
#ifdef HAVE_OPENGL
#include "SDL_opengl.h"
static SDL_bool shaders_supported;
static int current_shader = 0;
enum {
SHADER_COLOR,
SHADER_TEXTURE,
SHADER_TEXCOORDS,
NUM_SHADERS
};
typedef struct {
GLhandleARB program;
GLhandleARB vert_shader;
GLhandleARB frag_shader;
const char *vert_source;
const char *frag_source;
} ShaderData;
static ShaderData shaders[NUM_SHADERS] = {
/* SHADER_COLOR */
{ 0, 0, 0,
/* vertex shader */
"varying vec4 v_color;\n"
"\n"
"void main()\n"
"{\n"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
" v_color = gl_Color;\n"
"}",
/* fragment shader */
"varying vec4 v_color;\n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor = v_color;\n"
"}"
},
/* SHADER_TEXTURE */
{ 0, 0, 0,
/* vertex shader */
"varying vec4 v_color;\n"
"varying vec2 v_texCoord;\n"
"\n"
"void main()\n"
"{\n"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
" v_color = gl_Color;\n"
" v_texCoord = vec2(gl_MultiTexCoord0);\n"
"}",
/* fragment shader */
"varying vec4 v_color;\n"
"varying vec2 v_texCoord;\n"
"uniform sampler2D tex0;\n"
"\n"
"void main()\n"
"{\n"
" gl_FragColor = texture2D(tex0, v_texCoord) * v_color;\n"
"}"
},
/* SHADER_TEXCOORDS */
{ 0, 0, 0,
/* vertex shader */
"varying vec2 v_texCoord;\n"
"\n"
"void main()\n"
"{\n"
" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
" v_texCoord = vec2(gl_MultiTexCoord0);\n"
"}",
/* fragment shader */
"varying vec2 v_texCoord;\n"
"\n"
"void main()\n"
"{\n"
" vec4 color;\n"
" vec2 delta;\n"
" float dist;\n"
"\n"
" delta = vec2(0.5, 0.5) - v_texCoord;\n"
" dist = dot(delta, delta);\n"
"\n"
" color.r = v_texCoord.x;\n"
" color.g = v_texCoord.x * v_texCoord.y;\n"
" color.b = v_texCoord.y;\n"
" color.a = 1.0 - (dist * 4.0);\n"
" gl_FragColor = color;\n"
"}"
},
};
static PFNGLATTACHOBJECTARBPROC glAttachObjectARB;
static PFNGLCOMPILESHADERARBPROC glCompileShaderARB;
static PFNGLCREATEPROGRAMOBJECTARBPROC glCreateProgramObjectARB;
static PFNGLCREATESHADEROBJECTARBPROC glCreateShaderObjectARB;
static PFNGLDELETEOBJECTARBPROC glDeleteObjectARB;
static PFNGLGETINFOLOGARBPROC glGetInfoLogARB;
static PFNGLGETOBJECTPARAMETERIVARBPROC glGetObjectParameterivARB;
static PFNGLGETUNIFORMLOCATIONARBPROC glGetUniformLocationARB;
static PFNGLLINKPROGRAMARBPROC glLinkProgramARB;
static PFNGLSHADERSOURCEARBPROC glShaderSourceARB;
static PFNGLUNIFORM1IARBPROC glUniform1iARB;
static PFNGLUSEPROGRAMOBJECTARBPROC glUseProgramObjectARB;
static SDL_bool CompileShader(GLhandleARB shader, const char *source)
{
GLint status;
glShaderSourceARB(shader, 1, &source, NULL);
glCompileShaderARB(shader);
glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &status);
if (status == 0) {
GLint length;
char *info;
glGetObjectParameterivARB(shader, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length);
info = SDL_stack_alloc(char, length+1);
glGetInfoLogARB(shader, length, NULL, info);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to compile shader:\n%s\n%s", source, info);
SDL_stack_free(info);
return SDL_FALSE;
} else {
return SDL_TRUE;
}
}
static SDL_bool CompileShaderProgram(ShaderData *data)
{
const int num_tmus_bound = 4;
int i;
GLint location;
glGetError();
/* Create one program object to rule them all */
data->program = glCreateProgramObjectARB();
/* Create the vertex shader */
data->vert_shader = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB);
if (!CompileShader(data->vert_shader, data->vert_source)) {
return SDL_FALSE;
}
/* Create the fragment shader */
data->frag_shader = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB);
if (!CompileShader(data->frag_shader, data->frag_source)) {
return SDL_FALSE;
}
/* ... and in the darkness bind them */
glAttachObjectARB(data->program, data->vert_shader);
glAttachObjectARB(data->program, data->frag_shader);
glLinkProgramARB(data->program);
/* Set up some uniform variables */
glUseProgramObjectARB(data->program);
for (i = 0; i < num_tmus_bound; ++i) {
char tex_name[5];
SDL_snprintf(tex_name, SDL_arraysize(tex_name), "tex%d", i);
location = glGetUniformLocationARB(data->program, tex_name);
if (location >= 0) {
glUniform1iARB(location, i);
}
}
glUseProgramObjectARB(0);
return (glGetError() == GL_NO_ERROR) ? SDL_TRUE : SDL_FALSE;
}
static void DestroyShaderProgram(ShaderData *data)
{
if (shaders_supported) {
glDeleteObjectARB(data->vert_shader);
glDeleteObjectARB(data->frag_shader);
glDeleteObjectARB(data->program);
}
}
static SDL_bool InitShaders()
{
int i;
/* Check for shader support */
shaders_supported = SDL_FALSE;
if (SDL_GL_ExtensionSupported("GL_ARB_shader_objects") &&
SDL_GL_ExtensionSupported("GL_ARB_shading_language_100") &&
SDL_GL_ExtensionSupported("GL_ARB_vertex_shader") &&
SDL_GL_ExtensionSupported("GL_ARB_fragment_shader")) {
glAttachObjectARB = (PFNGLATTACHOBJECTARBPROC) SDL_GL_GetProcAddress("glAttachObjectARB");
glCompileShaderARB = (PFNGLCOMPILESHADERARBPROC) SDL_GL_GetProcAddress("glCompileShaderARB");
glCreateProgramObjectARB = (PFNGLCREATEPROGRAMOBJECTARBPROC) SDL_GL_GetProcAddress("glCreateProgramObjectARB");
glCreateShaderObjectARB = (PFNGLCREATESHADEROBJECTARBPROC) SDL_GL_GetProcAddress("glCreateShaderObjectARB");
glDeleteObjectARB = (PFNGLDELETEOBJECTARBPROC) SDL_GL_GetProcAddress("glDeleteObjectARB");
glGetInfoLogARB = (PFNGLGETINFOLOGARBPROC) SDL_GL_GetProcAddress("glGetInfoLogARB");
glGetObjectParameterivARB = (PFNGLGETOBJECTPARAMETERIVARBPROC) SDL_GL_GetProcAddress("glGetObjectParameterivARB");
glGetUniformLocationARB = (PFNGLGETUNIFORMLOCATIONARBPROC) SDL_GL_GetProcAddress("glGetUniformLocationARB");
glLinkProgramARB = (PFNGLLINKPROGRAMARBPROC) SDL_GL_GetProcAddress("glLinkProgramARB");
glShaderSourceARB = (PFNGLSHADERSOURCEARBPROC) SDL_GL_GetProcAddress("glShaderSourceARB");
glUniform1iARB = (PFNGLUNIFORM1IARBPROC) SDL_GL_GetProcAddress("glUniform1iARB");
glUseProgramObjectARB = (PFNGLUSEPROGRAMOBJECTARBPROC) SDL_GL_GetProcAddress("glUseProgramObjectARB");
if (glAttachObjectARB &&
glCompileShaderARB &&
glCreateProgramObjectARB &&
glCreateShaderObjectARB &&
glDeleteObjectARB &&
glGetInfoLogARB &&
glGetObjectParameterivARB &&
glGetUniformLocationARB &&
glLinkProgramARB &&
glShaderSourceARB &&
glUniform1iARB &&
glUseProgramObjectARB) {
shaders_supported = SDL_TRUE;
}
}
if (!shaders_supported) {
return SDL_FALSE;
}
/* Compile all the shaders */
for (i = 0; i < NUM_SHADERS; ++i) {
if (!CompileShaderProgram(&shaders[i])) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to compile shader!\n");
return SDL_FALSE;
}
}
/* We're done! */
return SDL_TRUE;
}
static void QuitShaders()
{
int i;
for (i = 0; i < NUM_SHADERS; ++i) {
DestroyShaderProgram(&shaders[i]);
}
}
/* Quick utility function for texture creation */
static int
power_of_two(int input)
{
int value = 1;
while (value < input) {
value <<= 1;
}
return value;
}
GLuint
SDL_GL_LoadTexture(SDL_Surface * surface, GLfloat * texcoord)
{
GLuint texture;
int w, h;
SDL_Surface *image;
SDL_Rect area;
SDL_BlendMode saved_mode;
/* Use the surface width and height expanded to powers of 2 */
w = power_of_two(surface->w);
h = power_of_two(surface->h);
texcoord[0] = 0.0f; /* Min X */
texcoord[1] = 0.0f; /* Min Y */
texcoord[2] = (GLfloat) surface->w / w; /* Max X */
texcoord[3] = (GLfloat) surface->h / h; /* Max Y */
image = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32,
#if SDL_BYTEORDER == SDL_LIL_ENDIAN /* OpenGL RGBA masks */
0x000000FF,
0x0000FF00, 0x00FF0000, 0xFF000000
#else
0xFF000000,
0x00FF0000, 0x0000FF00, 0x000000FF
#endif
);
if (image == NULL) {
return 0;
}
/* Save the alpha blending attributes */
SDL_GetSurfaceBlendMode(surface, &saved_mode);
SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);
/* Copy the surface into the GL texture image */
area.x = 0;
area.y = 0;
area.w = surface->w;
area.h = surface->h;
SDL_BlitSurface(surface, &area, image, &area);
/* Restore the alpha blending attributes */
SDL_SetSurfaceBlendMode(surface, saved_mode);
/* Create an OpenGL texture for the image */
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels);
SDL_FreeSurface(image); /* No longer needed */
return texture;
}
/* A general OpenGL initialization function. Sets all of the initial parameters. */
void InitGL(int Width, int Height) /* We call this right after our OpenGL window is created. */
{
GLdouble aspect;
glViewport(0, 0, Width, Height);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); /* This Will Clear The Background Color To Black */
glClearDepth(1.0); /* Enables Clearing Of The Depth Buffer */
glDepthFunc(GL_LESS); /* The Type Of Depth Test To Do */
glEnable(GL_DEPTH_TEST); /* Enables Depth Testing */
glShadeModel(GL_SMOOTH); /* Enables Smooth Color Shading */
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); /* Reset The Projection Matrix */
aspect = (GLdouble)Width / Height;
glOrtho(-3.0, 3.0, -3.0 / aspect, 3.0 / aspect, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}
/* The main drawing function. */
void DrawGLScene(SDL_Window *window, GLuint texture, GLfloat * texcoord)
{
/* Texture coordinate lookup, to make it simple */
enum {
MINX,
MINY,
MAXX,
MAXY
};
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* Clear The Screen And The Depth Buffer */
glLoadIdentity(); /* Reset The View */
glTranslatef(-1.5f,0.0f,0.0f); /* Move Left 1.5 Units */
/* draw a triangle (in smooth coloring mode) */
glBegin(GL_POLYGON); /* start drawing a polygon */
glColor3f(1.0f,0.0f,0.0f); /* Set The Color To Red */
glVertex3f( 0.0f, 1.0f, 0.0f); /* Top */
glColor3f(0.0f,1.0f,0.0f); /* Set The Color To Green */
glVertex3f( 1.0f,-1.0f, 0.0f); /* Bottom Right */
glColor3f(0.0f,0.0f,1.0f); /* Set The Color To Blue */
glVertex3f(-1.0f,-1.0f, 0.0f); /* Bottom Left */
glEnd(); /* we're done with the polygon (smooth color interpolation) */
glTranslatef(3.0f,0.0f,0.0f); /* Move Right 3 Units */
/* Enable blending */
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
/* draw a textured square (quadrilateral) */
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glColor3f(1.0f,1.0f,1.0f);
if (shaders_supported) {
glUseProgramObjectARB(shaders[current_shader].program);
}
glBegin(GL_QUADS); /* start drawing a polygon (4 sided) */
glTexCoord2f(texcoord[MINX], texcoord[MINY]);
glVertex3f(-1.0f, 1.0f, 0.0f); /* Top Left */
glTexCoord2f(texcoord[MAXX], texcoord[MINY]);
glVertex3f( 1.0f, 1.0f, 0.0f); /* Top Right */
glTexCoord2f(texcoord[MAXX], texcoord[MAXY]);
glVertex3f( 1.0f,-1.0f, 0.0f); /* Bottom Right */
glTexCoord2f(texcoord[MINX], texcoord[MAXY]);
glVertex3f(-1.0f,-1.0f, 0.0f); /* Bottom Left */
glEnd(); /* done with the polygon */
if (shaders_supported) {
glUseProgramObjectARB(0);
}
glDisable(GL_TEXTURE_2D);
/* swap buffers to display, since we're double buffered. */
SDL_GL_SwapWindow(window);
}
int main(int argc, char **argv)
{
int done;
SDL_Window *window;
SDL_Surface *surface;
GLuint texture;
GLfloat texcoords[4];
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize SDL for video output */
if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to initialize SDL: %s\n", SDL_GetError());
exit(1);
}
/* Create a 640x480 OpenGL screen */
window = SDL_CreateWindow( "Shader Demo", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL );
if ( !window ) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create OpenGL window: %s\n", SDL_GetError());
SDL_Quit();
exit(2);
}
if ( !SDL_GL_CreateContext(window)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to create OpenGL context: %s\n", SDL_GetError());
SDL_Quit();
exit(2);
}
surface = SDL_LoadBMP("icon.bmp");
if ( ! surface ) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unable to load icon.bmp: %s\n", SDL_GetError());
SDL_Quit();
exit(3);
}
texture = SDL_GL_LoadTexture(surface, texcoords);
SDL_FreeSurface(surface);
/* Loop, drawing and checking events */
InitGL(640, 480);
if (InitShaders()) {
SDL_Log("Shaders supported, press SPACE to cycle them.\n");
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shaders not supported!\n");
}
done = 0;
while ( ! done ) {
DrawGLScene(window, texture, texcoords);
/* This could go in a separate function */
{ SDL_Event event;
while ( SDL_PollEvent(&event) ) {
if ( event.type == SDL_QUIT ) {
done = 1;
}
if ( event.type == SDL_KEYDOWN ) {
if ( event.key.keysym.sym == SDLK_SPACE ) {
current_shader = (current_shader + 1) % NUM_SHADERS;
}
if ( event.key.keysym.sym == SDLK_ESCAPE ) {
done = 1;
}
}
}
}
}
QuitShaders();
SDL_Quit();
return 1;
}
#else /* HAVE_OPENGL */
int
main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No OpenGL support on this system\n");
return 1;
}
#endif /* HAVE_OPENGL */
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testshader.c | C | apache-2.0 | 15,780 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
#include "SDL.h"
#include "SDL_shape.h"
#define SHAPED_WINDOW_X 150
#define SHAPED_WINDOW_Y 150
#define SHAPED_WINDOW_DIMENSION 640
typedef struct LoadedPicture {
SDL_Surface *surface;
SDL_Texture *texture;
SDL_WindowShapeMode mode;
const char* name;
} LoadedPicture;
void render(SDL_Renderer *renderer,SDL_Texture *texture,SDL_Rect texture_dimensions)
{
/* Clear render-target to blue. */
SDL_SetRenderDrawColor(renderer,0x00,0x00,0xff,0xff);
SDL_RenderClear(renderer);
/* Render the texture. */
SDL_RenderCopy(renderer,texture,&texture_dimensions,&texture_dimensions);
SDL_RenderPresent(renderer);
}
int main(int argc,char** argv)
{
Uint8 num_pictures;
LoadedPicture* pictures;
int i, j;
SDL_PixelFormat* format = NULL;
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Color black = {0,0,0,0xff};
SDL_Event event;
int should_exit = 0;
unsigned int current_picture;
int button_down;
Uint32 pixelFormat = 0;
int access = 0;
SDL_Rect texture_dimensions;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if(argc < 2) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Shape requires at least one bitmap file as argument.");
exit(-1);
}
if(SDL_VideoInit(NULL) == -1) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not initialize SDL video.");
exit(-2);
}
num_pictures = argc - 1;
pictures = (LoadedPicture *)SDL_malloc(sizeof(LoadedPicture)*num_pictures);
if (!pictures) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not allocate memory.");
exit(1);
}
for(i=0;i<num_pictures;i++)
pictures[i].surface = NULL;
for(i=0;i<num_pictures;i++) {
pictures[i].surface = SDL_LoadBMP(argv[i+1]);
pictures[i].name = argv[i+1];
if(pictures[i].surface == NULL) {
for(j=0;j<num_pictures;j++)
SDL_FreeSurface(pictures[j].surface);
SDL_free(pictures);
SDL_VideoQuit();
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not load surface from named bitmap file: %s", argv[i+1]);
exit(-3);
}
format = pictures[i].surface->format;
if(SDL_ISPIXELFORMAT_ALPHA(format->format)) {
pictures[i].mode.mode = ShapeModeBinarizeAlpha;
pictures[i].mode.parameters.binarizationCutoff = 255;
}
else {
pictures[i].mode.mode = ShapeModeColorKey;
pictures[i].mode.parameters.colorKey = black;
}
}
window = SDL_CreateShapedWindow("SDL_Shape test",
SHAPED_WINDOW_X, SHAPED_WINDOW_Y,
SHAPED_WINDOW_DIMENSION,SHAPED_WINDOW_DIMENSION,
0);
SDL_SetWindowPosition(window, SHAPED_WINDOW_X, SHAPED_WINDOW_Y);
if(window == NULL) {
for(i=0;i<num_pictures;i++)
SDL_FreeSurface(pictures[i].surface);
SDL_free(pictures);
SDL_VideoQuit();
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create shaped window for SDL_Shape.");
exit(-4);
}
renderer = SDL_CreateRenderer(window,-1,0);
if (!renderer) {
SDL_DestroyWindow(window);
for(i=0;i<num_pictures;i++)
SDL_FreeSurface(pictures[i].surface);
SDL_free(pictures);
SDL_VideoQuit();
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create rendering context for SDL_Shape window.");
exit(-5);
}
for(i=0;i<num_pictures;i++)
pictures[i].texture = NULL;
for(i=0;i<num_pictures;i++) {
pictures[i].texture = SDL_CreateTextureFromSurface(renderer,pictures[i].surface);
if(pictures[i].texture == NULL) {
for(i=0;i<num_pictures;i++)
if(pictures[i].texture != NULL)
SDL_DestroyTexture(pictures[i].texture);
for(i=0;i<num_pictures;i++)
SDL_FreeSurface(pictures[i].surface);
SDL_free(pictures);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_VideoQuit();
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Could not create texture for SDL_shape.");
exit(-6);
}
}
should_exit = 0;
current_picture = 0;
button_down = 0;
texture_dimensions.h = 0;
texture_dimensions.w = 0;
texture_dimensions.x = 0;
texture_dimensions.y = 0;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Changing to shaped bmp: %s", pictures[current_picture].name);
SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
while(should_exit == 0) {
while (SDL_PollEvent(&event)) {
if(event.type == SDL_KEYDOWN) {
button_down = 1;
if(event.key.keysym.sym == SDLK_ESCAPE) {
should_exit = 1;
break;
}
}
if(button_down && event.type == SDL_KEYUP) {
button_down = 0;
current_picture += 1;
if(current_picture >= num_pictures)
current_picture = 0;
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Changing to shaped bmp: %s", pictures[current_picture].name);
SDL_QueryTexture(pictures[current_picture].texture,(Uint32 *)&pixelFormat,(int *)&access,&texture_dimensions.w,&texture_dimensions.h);
SDL_SetWindowSize(window,texture_dimensions.w,texture_dimensions.h);
SDL_SetWindowShape(window,pictures[current_picture].surface,&pictures[current_picture].mode);
}
if (event.type == SDL_QUIT) {
should_exit = 1;
break;
}
}
render(renderer,pictures[current_picture].texture,texture_dimensions);
SDL_Delay(10);
}
/* Free the textures. */
for(i=0;i<num_pictures;i++)
SDL_DestroyTexture(pictures[i].texture);
SDL_DestroyRenderer(renderer);
/* Destroy the window. */
SDL_DestroyWindow(window);
/* Free the original surfaces backing the textures. */
for(i=0;i<num_pictures;i++)
SDL_FreeSurface(pictures[i].surface);
SDL_free(pictures);
/* Call SDL_VideoQuit() before quitting. */
SDL_VideoQuit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testshape.c | C | apache-2.0 | 7,095 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test.h"
#include "SDL_test_common.h"
#define NUM_SPRITES 100
#define MAX_SPEED 1
static SDLTest_CommonState *state;
static int num_sprites;
static SDL_Texture **sprites;
static SDL_bool cycle_color;
static SDL_bool cycle_alpha;
static int cycle_direction = 1;
static int current_alpha = 0;
static int current_color = 0;
static SDL_Rect *positions;
static SDL_Rect *velocities;
static int sprite_w, sprite_h;
static SDL_BlendMode blendMode = SDL_BLENDMODE_BLEND;
static Uint32 next_fps_check, frames;
static const Uint32 fps_check_delay = 5000;
/* Number of iterations to move sprites - used for visual tests. */
/* -1: infinite random moves (default); >=0: enables N deterministic moves */
static int iterations = -1;
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_free(sprites);
SDL_free(positions);
SDL_free(velocities);
SDLTest_CommonQuit(state);
exit(rc);
}
int
LoadSprite(const char *file)
{
int i;
SDL_Surface *temp;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError());
return (-1);
}
sprite_w = temp->w;
sprite_h = temp->h;
/* Set transparent pixel as the pixel at (0,0) */
if (temp->format->palette) {
SDL_SetColorKey(temp, 1, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, 1, (*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, 1, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, 1, (*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, 1, *(Uint32 *) temp->pixels);
break;
}
}
/* Create textures from the image */
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
sprites[i] = SDL_CreateTextureFromSurface(renderer, temp);
if (!sprites[i]) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return (-1);
}
if (SDL_SetTextureBlendMode(sprites[i], blendMode) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set blend mode: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
SDL_DestroyTexture(sprites[i]);
return (-1);
}
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return (0);
}
void
MoveSprites(SDL_Renderer * renderer, SDL_Texture * sprite)
{
int i;
SDL_Rect viewport, temp;
SDL_Rect *position, *velocity;
/* Query the sizes */
SDL_RenderGetViewport(renderer, &viewport);
/* Cycle the color and alpha, if desired */
if (cycle_color) {
current_color += cycle_direction;
if (current_color < 0) {
current_color = 0;
cycle_direction = -cycle_direction;
}
if (current_color > 255) {
current_color = 255;
cycle_direction = -cycle_direction;
}
SDL_SetTextureColorMod(sprite, 255, (Uint8) current_color,
(Uint8) current_color);
}
if (cycle_alpha) {
current_alpha += cycle_direction;
if (current_alpha < 0) {
current_alpha = 0;
cycle_direction = -cycle_direction;
}
if (current_alpha > 255) {
current_alpha = 255;
cycle_direction = -cycle_direction;
}
SDL_SetTextureAlphaMod(sprite, (Uint8) current_alpha);
}
/* Draw a gray background */
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
/* Test points */
SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF);
SDL_RenderDrawPoint(renderer, 0, 0);
SDL_RenderDrawPoint(renderer, viewport.w-1, 0);
SDL_RenderDrawPoint(renderer, 0, viewport.h-1);
SDL_RenderDrawPoint(renderer, viewport.w-1, viewport.h-1);
/* Test horizontal and vertical lines */
SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
SDL_RenderDrawLine(renderer, 1, 0, viewport.w-2, 0);
SDL_RenderDrawLine(renderer, 1, viewport.h-1, viewport.w-2, viewport.h-1);
SDL_RenderDrawLine(renderer, 0, 1, 0, viewport.h-2);
SDL_RenderDrawLine(renderer, viewport.w-1, 1, viewport.w-1, viewport.h-2);
/* Test fill and copy */
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
temp.x = 1;
temp.y = 1;
temp.w = sprite_w;
temp.h = sprite_h;
SDL_RenderFillRect(renderer, &temp);
SDL_RenderCopy(renderer, sprite, NULL, &temp);
temp.x = viewport.w-sprite_w-1;
temp.y = 1;
temp.w = sprite_w;
temp.h = sprite_h;
SDL_RenderFillRect(renderer, &temp);
SDL_RenderCopy(renderer, sprite, NULL, &temp);
temp.x = 1;
temp.y = viewport.h-sprite_h-1;
temp.w = sprite_w;
temp.h = sprite_h;
SDL_RenderFillRect(renderer, &temp);
SDL_RenderCopy(renderer, sprite, NULL, &temp);
temp.x = viewport.w-sprite_w-1;
temp.y = viewport.h-sprite_h-1;
temp.w = sprite_w;
temp.h = sprite_h;
SDL_RenderFillRect(renderer, &temp);
SDL_RenderCopy(renderer, sprite, NULL, &temp);
/* Test diagonal lines */
SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
SDL_RenderDrawLine(renderer, sprite_w, sprite_h,
viewport.w-sprite_w-2, viewport.h-sprite_h-2);
SDL_RenderDrawLine(renderer, viewport.w-sprite_w-2, sprite_h,
sprite_w, viewport.h-sprite_h-2);
/* Conditionally move the sprites, bounce at the wall */
if (iterations == -1 || iterations > 0) {
for (i = 0; i < num_sprites; ++i) {
position = &positions[i];
velocity = &velocities[i];
position->x += velocity->x;
if ((position->x < 0) || (position->x >= (viewport.w - sprite_w))) {
velocity->x = -velocity->x;
position->x += velocity->x;
}
position->y += velocity->y;
if ((position->y < 0) || (position->y >= (viewport.h - sprite_h))) {
velocity->y = -velocity->y;
position->y += velocity->y;
}
}
/* Countdown sprite-move iterations and disable color changes at iteration end - used for visual tests. */
if (iterations > 0) {
iterations--;
if (iterations == 0) {
cycle_alpha = SDL_FALSE;
cycle_color = SDL_FALSE;
}
}
}
/* Draw sprites */
for (i = 0; i < num_sprites; ++i) {
position = &positions[i];
/* Blit the sprite onto the screen */
SDL_RenderCopy(renderer, sprite, NULL, position);
}
/* Update the screen! */
SDL_RenderPresent(renderer);
}
void
loop()
{
Uint32 now;
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
MoveSprites(state->renderers[i], sprites[i]);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
frames++;
now = SDL_GetTicks();
if (SDL_TICKS_PASSED(now, next_fps_check)) {
/* Print out some timing information */
const Uint32 then = next_fps_check - fps_check_delay;
const double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
next_fps_check = now + fps_check_delay;
frames = 0;
}
}
int
main(int argc, char *argv[])
{
int i;
Uint64 seed;
const char *icon = "icon.bmp";
/* Initialize parameters */
num_sprites = NUM_SPRITES;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--blend") == 0) {
if (argv[i + 1]) {
if (SDL_strcasecmp(argv[i + 1], "none") == 0) {
blendMode = SDL_BLENDMODE_NONE;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "blend") == 0) {
blendMode = SDL_BLENDMODE_BLEND;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "add") == 0) {
blendMode = SDL_BLENDMODE_ADD;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "mod") == 0) {
blendMode = SDL_BLENDMODE_MOD;
consumed = 2;
} else if (SDL_strcasecmp(argv[i + 1], "sub") == 0) {
blendMode = SDL_ComposeCustomBlendMode(SDL_BLENDFACTOR_SRC_ALPHA, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_SUBTRACT, SDL_BLENDFACTOR_ZERO, SDL_BLENDFACTOR_ONE, SDL_BLENDOPERATION_SUBTRACT);
consumed = 2;
}
}
} else if (SDL_strcasecmp(argv[i], "--iterations") == 0) {
if (argv[i + 1]) {
iterations = SDL_atoi(argv[i + 1]);
if (iterations < -1) iterations = -1;
consumed = 2;
}
} else if (SDL_strcasecmp(argv[i], "--cyclecolor") == 0) {
cycle_color = SDL_TRUE;
consumed = 1;
} else if (SDL_strcasecmp(argv[i], "--cyclealpha") == 0) {
cycle_alpha = SDL_TRUE;
consumed = 1;
} else if (SDL_isdigit(*argv[i])) {
num_sprites = SDL_atoi(argv[i]);
consumed = 1;
} else if (argv[i][0] != '-') {
icon = argv[i];
consumed = 1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--blend none|blend|add|mod]", "[--cyclecolor]", "[--cyclealpha]", "[--iterations N]", "[num_sprites]", "[icon.bmp]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
/* Create the windows, initialize the renderers, and load the textures */
sprites =
(SDL_Texture **) SDL_malloc(state->num_windows * sizeof(*sprites));
if (!sprites) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
quit(2);
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
if (LoadSprite(icon) < 0) {
quit(2);
}
/* Allocate memory for the sprite info */
positions = (SDL_Rect *) SDL_malloc(num_sprites * sizeof(SDL_Rect));
velocities = (SDL_Rect *) SDL_malloc(num_sprites * sizeof(SDL_Rect));
if (!positions || !velocities) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory!\n");
quit(2);
}
/* Position sprites and set their velocities using the fuzzer */
if (iterations >= 0) {
/* Deterministic seed - used for visual tests */
seed = (Uint64)iterations;
} else {
/* Pseudo-random seed generated from the time */
seed = (Uint64)time(NULL);
}
SDLTest_FuzzerInit(seed);
for (i = 0; i < num_sprites; ++i) {
positions[i].x = SDLTest_RandomIntegerInRange(0, state->window_w - sprite_w);
positions[i].y = SDLTest_RandomIntegerInRange(0, state->window_h - sprite_h);
positions[i].w = sprite_w;
positions[i].h = sprite_h;
velocities[i].x = 0;
velocities[i].y = 0;
while (!velocities[i].x && !velocities[i].y) {
velocities[i].x = SDLTest_RandomIntegerInRange(-MAX_SPEED, MAX_SPEED);
velocities[i].y = SDLTest_RandomIntegerInRange(-MAX_SPEED, MAX_SPEED);
}
}
/* Main render loop */
frames = 0;
next_fps_check = SDL_GetTicks() + fps_check_delay;
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testsprite2.c | C | apache-2.0 | 13,416 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Move N sprites around on the screen as fast as possible */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define NUM_SPRITES 100
#define MAX_SPEED 1
static SDL_Texture *sprite;
static SDL_Rect positions[NUM_SPRITES];
static SDL_Rect velocities[NUM_SPRITES];
static int sprite_w, sprite_h;
SDL_Renderer *renderer;
int done;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
int
LoadSprite(char *file, SDL_Renderer *renderer)
{
SDL_Surface *temp;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", file, SDL_GetError());
return (-1);
}
sprite_w = temp->w;
sprite_h = temp->h;
/* Set transparent pixel as the pixel at (0,0) */
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
/* Create textures from the image */
sprite = SDL_CreateTextureFromSurface(renderer, temp);
if (!sprite) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return (-1);
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return (0);
}
void
MoveSprites(SDL_Renderer * renderer, SDL_Texture * sprite)
{
int i;
int window_w = WINDOW_WIDTH;
int window_h = WINDOW_HEIGHT;
SDL_Rect *position, *velocity;
/* Draw a gray background */
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
/* Move the sprite, bounce at the wall, and draw */
for (i = 0; i < NUM_SPRITES; ++i) {
position = &positions[i];
velocity = &velocities[i];
position->x += velocity->x;
if ((position->x < 0) || (position->x >= (window_w - sprite_w))) {
velocity->x = -velocity->x;
position->x += velocity->x;
}
position->y += velocity->y;
if ((position->y < 0) || (position->y >= (window_h - sprite_h))) {
velocity->y = -velocity->y;
position->y += velocity->y;
}
/* Blit the sprite onto the screen */
SDL_RenderCopy(renderer, sprite, NULL, position);
}
/* Update the screen! */
SDL_RenderPresent(renderer);
}
void loop()
{
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT || event.type == SDL_KEYDOWN) {
done = 1;
}
}
MoveSprites(renderer, sprite);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
SDL_Window *window;
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_CreateWindowAndRenderer(WINDOW_WIDTH, WINDOW_HEIGHT, 0, &window, &renderer) < 0) {
quit(2);
}
if (LoadSprite("icon.bmp", renderer) < 0) {
quit(2);
}
/* Initialize the sprite positions */
srand(time(NULL));
for (i = 0; i < NUM_SPRITES; ++i) {
positions[i].x = rand() % (WINDOW_WIDTH - sprite_w);
positions[i].y = rand() % (WINDOW_HEIGHT - sprite_h);
positions[i].w = sprite_w;
positions[i].h = sprite_h;
velocities[i].x = 0;
velocities[i].y = 0;
while (!velocities[i].x && !velocities[i].y) {
velocities[i].x = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
velocities[i].y = (rand() % (MAX_SPEED * 2 + 1)) - MAX_SPEED;
}
}
/* Main render loop */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
quit(0);
return 0; /* to prevent compiler warning */
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testspriteminimal.c | C | apache-2.0 | 5,098 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/********************************************************************************
* *
* Running moose :) Coded by Mike Gorchak. *
* *
********************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL.h"
#define MOOSEPIC_W 64
#define MOOSEPIC_H 88
#define MOOSEFRAME_SIZE (MOOSEPIC_W * MOOSEPIC_H)
#define MOOSEFRAMES_COUNT 10
SDL_Color MooseColors[84] = {
{49, 49, 49, 255}, {66, 24, 0, 255}, {66, 33, 0, 255}, {66, 66, 66, 255},
{66, 115, 49, 255}, {74, 33, 0, 255}, {74, 41, 16, 255}, {82, 33, 8, 255},
{82, 41, 8, 255}, {82, 49, 16, 255}, {82, 82, 82, 255}, {90, 41, 8, 255},
{90, 41, 16, 255}, {90, 57, 24, 255}, {99, 49, 16, 255}, {99, 66, 24, 255},
{99, 66, 33, 255}, {99, 74, 33, 255}, {107, 57, 24, 255}, {107, 82, 41, 255},
{115, 57, 33, 255}, {115, 66, 33, 255}, {115, 66, 41, 255}, {115, 74, 0, 255},
{115, 90, 49, 255}, {115, 115, 115, 255}, {123, 82, 0, 255}, {123, 99, 57, 255},
{132, 66, 41, 255}, {132, 74, 41, 255}, {132, 90, 8, 255}, {132, 99, 33, 255},
{132, 99, 66, 255}, {132, 107, 66, 255}, {140, 74, 49, 255}, {140, 99, 16, 255},
{140, 107, 74, 255}, {140, 115, 74, 255}, {148, 107, 24, 255}, {148, 115, 82, 255},
{148, 123, 74, 255}, {148, 123, 90, 255}, {156, 115, 33, 255}, {156, 115, 90, 255},
{156, 123, 82, 255}, {156, 132, 82, 255}, {156, 132, 99, 255}, {156, 156, 156, 255},
{165, 123, 49, 255}, {165, 123, 90, 255}, {165, 132, 82, 255}, {165, 132, 90, 255},
{165, 132, 99, 255}, {165, 140, 90, 255}, {173, 132, 57, 255}, {173, 132, 99, 255},
{173, 140, 107, 255}, {173, 140, 115, 255}, {173, 148, 99, 255}, {173, 173, 173, 255},
{181, 140, 74, 255}, {181, 148, 115, 255}, {181, 148, 123, 255}, {181, 156, 107, 255},
{189, 148, 123, 255}, {189, 156, 82, 255}, {189, 156, 123, 255}, {189, 156, 132, 255},
{189, 189, 189, 255}, {198, 156, 123, 255}, {198, 165, 132, 255}, {206, 165, 99, 255},
{206, 165, 132, 255}, {206, 173, 140, 255}, {206, 206, 206, 255}, {214, 173, 115, 255},
{214, 173, 140, 255}, {222, 181, 148, 255}, {222, 189, 132, 255}, {222, 189, 156, 255},
{222, 222, 222, 255}, {231, 198, 165, 255}, {231, 231, 231, 255}, {239, 206, 173, 255}
};
Uint8 MooseFrames[MOOSEFRAMES_COUNT][MOOSEFRAME_SIZE];
SDL_Renderer *renderer;
int frame;
SDL_Texture *MooseTexture;
SDL_bool done = SDL_FALSE;
void quit(int rc)
{
SDL_Quit();
exit(rc);
}
void UpdateTexture(SDL_Texture *texture, int frame)
{
SDL_Color *color;
Uint8 *src;
Uint32 *dst;
int row, col;
void *pixels;
int pitch;
if (SDL_LockTexture(texture, NULL, &pixels, &pitch) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't lock texture: %s\n", SDL_GetError());
quit(5);
}
src = MooseFrames[frame];
for (row = 0; row < MOOSEPIC_H; ++row) {
dst = (Uint32*)((Uint8*)pixels + row * pitch);
for (col = 0; col < MOOSEPIC_W; ++col) {
color = &MooseColors[*src++];
*dst++ = (0xFF000000|(color->r<<16)|(color->g<<8)|color->b);
}
}
SDL_UnlockTexture(texture);
}
void
loop()
{
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_ESCAPE) {
done = SDL_TRUE;
}
break;
case SDL_QUIT:
done = SDL_TRUE;
break;
}
}
frame = (frame + 1) % MOOSEFRAMES_COUNT;
UpdateTexture(MooseTexture, frame);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, MooseTexture, NULL, NULL);
SDL_RenderPresent(renderer);
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char **argv)
{
SDL_Window *window;
SDL_RWops *handle;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return 1;
}
/* load the moose images */
handle = SDL_RWFromFile("moose.dat", "rb");
if (handle == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Can't find the file moose.dat !\n");
quit(2);
}
SDL_RWread(handle, MooseFrames, MOOSEFRAME_SIZE, MOOSEFRAMES_COUNT);
SDL_RWclose(handle);
/* Create the window and renderer */
window = SDL_CreateWindow("Happy Moose",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
MOOSEPIC_W*4, MOOSEPIC_H*4,
SDL_WINDOW_RESIZABLE);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create window: %s\n", SDL_GetError());
quit(3);
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create renderer: %s\n", SDL_GetError());
quit(4);
}
MooseTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, MOOSEPIC_W, MOOSEPIC_H);
if (!MooseTexture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
quit(5);
}
/* Loop, waiting for QUIT or the escape key */
frame = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_DestroyRenderer(renderer);
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/teststreaming.c | C | apache-2.0 | 6,357 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL threading code */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include "SDL.h"
static SDL_TLSID tls;
static int alive = 0;
static int testprio = 0;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
static const char *
getprioritystr(SDL_ThreadPriority priority)
{
switch(priority)
{
case SDL_THREAD_PRIORITY_LOW: return "SDL_THREAD_PRIORITY_LOW";
case SDL_THREAD_PRIORITY_NORMAL: return "SDL_THREAD_PRIORITY_NORMAL";
case SDL_THREAD_PRIORITY_HIGH: return "SDL_THREAD_PRIORITY_HIGH";
case SDL_THREAD_PRIORITY_TIME_CRITICAL: return "SDL_THREAD_PRIORITY_TIME_CRITICAL";
}
return "???";
}
int SDLCALL
ThreadFunc(void *data)
{
SDL_ThreadPriority prio = SDL_THREAD_PRIORITY_NORMAL;
SDL_TLSSet(tls, "baby thread", NULL);
SDL_Log("Started thread %s: My thread id is %lu, thread data = %s\n",
(char *) data, SDL_ThreadID(), (const char *)SDL_TLSGet(tls));
while (alive) {
SDL_Log("Thread '%s' is alive!\n", (char *) data);
if (testprio) {
SDL_Log("SDL_SetThreadPriority(%s):%d\n", getprioritystr(prio), SDL_SetThreadPriority(prio));
if (++prio > SDL_THREAD_PRIORITY_TIME_CRITICAL)
prio = SDL_THREAD_PRIORITY_LOW;
}
SDL_Delay(1 * 1000);
}
SDL_Log("Thread '%s' exiting!\n", (char *) data);
return (0);
}
static void
killed(int sig)
{
SDL_Log("Killed with SIGTERM, waiting 5 seconds to exit\n");
SDL_Delay(5 * 1000);
alive = 0;
quit(0);
}
int
main(int argc, char *argv[])
{
int arg = 1;
SDL_Thread *thread;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
while (argv[arg] && *argv[arg] == '-') {
if (SDL_strcmp(argv[arg], "--prio") == 0) {
testprio = 1;
}
++arg;
}
tls = SDL_TLSCreate();
SDL_assert(tls);
SDL_TLSSet(tls, "main thread", NULL);
SDL_Log("Main thread data initially: %s\n", (const char *)SDL_TLSGet(tls));
alive = 1;
thread = SDL_CreateThread(ThreadFunc, "One", "#1");
if (thread == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError());
quit(1);
}
SDL_Delay(5 * 1000);
SDL_Log("Waiting for thread #1\n");
alive = 0;
SDL_WaitThread(thread, NULL);
SDL_Log("Main thread data finally: %s\n", (const char *)SDL_TLSGet(tls));
alive = 1;
signal(SIGTERM, killed);
thread = SDL_CreateThread(ThreadFunc, "Two", "#2");
if (thread == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError());
quit(1);
}
raise(SIGTERM);
SDL_Quit(); /* Never reached */
return (0); /* Never reached */
}
| YifuLiu/AliOS-Things | components/SDL2/test/testthread.c | C | apache-2.0 | 3,534 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Test program to check the resolution of the SDL timer on the current
platform
*/
#include <stdlib.h>
#include <stdio.h>
#include "SDL.h"
#define DEFAULT_RESOLUTION 1
static int ticks = 0;
static Uint32 SDLCALL
ticktock(Uint32 interval, void *param)
{
++ticks;
return (interval);
}
static Uint32 SDLCALL
callback(Uint32 interval, void *param)
{
SDL_Log("Timer %d : param = %d\n", interval, (int) (uintptr_t) param);
return interval;
}
int
main(int argc, char *argv[])
{
int i, desired;
SDL_TimerID t1, t2, t3;
Uint32 start32, now32;
Uint64 start, now;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
if (SDL_Init(SDL_INIT_TIMER) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
/* Start the timer */
desired = 0;
if (argv[1]) {
desired = atoi(argv[1]);
}
if (desired == 0) {
desired = DEFAULT_RESOLUTION;
}
t1 = SDL_AddTimer(desired, ticktock, NULL);
/* Wait 10 seconds */
SDL_Log("Waiting 10 seconds\n");
SDL_Delay(10 * 1000);
/* Stop the timer */
SDL_RemoveTimer(t1);
/* Print the results */
if (ticks) {
SDL_Log("Timer resolution: desired = %d ms, actual = %f ms\n",
desired, (double) (10 * 1000) / ticks);
}
/* Test multiple timers */
SDL_Log("Testing multiple timers...\n");
t1 = SDL_AddTimer(100, callback, (void *) 1);
if (!t1)
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create timer 1: %s\n", SDL_GetError());
t2 = SDL_AddTimer(50, callback, (void *) 2);
if (!t2)
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create timer 2: %s\n", SDL_GetError());
t3 = SDL_AddTimer(233, callback, (void *) 3);
if (!t3)
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,"Could not create timer 3: %s\n", SDL_GetError());
/* Wait 10 seconds */
SDL_Log("Waiting 10 seconds\n");
SDL_Delay(10 * 1000);
SDL_Log("Removing timer 1 and waiting 5 more seconds\n");
SDL_RemoveTimer(t1);
SDL_Delay(5 * 1000);
SDL_RemoveTimer(t2);
SDL_RemoveTimer(t3);
start = SDL_GetPerformanceCounter();
for (i = 0; i < 1000000; ++i) {
ticktock(0, NULL);
}
now = SDL_GetPerformanceCounter();
SDL_Log("1 million iterations of ticktock took %f ms\n", (double)((now - start)*1000) / SDL_GetPerformanceFrequency());
SDL_Log("Performance counter frequency: %"SDL_PRIu64"\n", SDL_GetPerformanceFrequency());
start32 = SDL_GetTicks();
start = SDL_GetPerformanceCounter();
SDL_Delay(1000);
now = SDL_GetPerformanceCounter();
now32 = SDL_GetTicks();
SDL_Log("Delay 1 second = %d ms in ticks, %f ms according to performance counter\n", (now32-start32), (double)((now - start)*1000) / SDL_GetPerformanceFrequency());
SDL_Quit();
return (0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testtimer.c | C | apache-2.0 | 3,424 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Test program to compare the compile-time version of SDL with the linked
version of SDL
*/
#include <stdio.h>
#include <stdlib.h>
#include "SDL.h"
#include "SDL_revision.h"
int
main(int argc, char *argv[])
{
SDL_version compiled;
SDL_version linked;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
#if SDL_VERSION_ATLEAST(2, 0, 0)
SDL_Log("Compiled with SDL 2.0 or newer\n");
#else
SDL_Log("Compiled with SDL older than 2.0\n");
#endif
SDL_VERSION(&compiled);
SDL_Log("Compiled version: %d.%d.%d.%d (%s)\n",
compiled.major, compiled.minor, compiled.patch,
SDL_REVISION_NUMBER, SDL_REVISION);
SDL_GetVersion(&linked);
SDL_Log("Linked version: %d.%d.%d.%d (%s)\n",
linked.major, linked.minor, linked.patch,
SDL_GetRevisionNumber(), SDL_GetRevision());
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/testver.c | C | apache-2.0 | 1,351 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple program: Check viewports */
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test.h"
#include "SDL_test_common.h"
static SDLTest_CommonState *state;
static SDL_Rect viewport;
static int done, j;
static SDL_bool use_target = SDL_FALSE;
#ifdef __EMSCRIPTEN__
static Uint32 wait_start;
#endif
static SDL_Texture *sprite;
static int sprite_w, sprite_h;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
int
LoadSprite(char *file, SDL_Renderer *renderer)
{
SDL_Surface *temp;
/* Load the sprite image */
temp = SDL_LoadBMP(file);
if (temp == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", file, SDL_GetError());
return (-1);
}
sprite_w = temp->w;
sprite_h = temp->h;
/* Set transparent pixel as the pixel at (0,0) */
if (temp->format->palette) {
SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels);
} else {
switch (temp->format->BitsPerPixel) {
case 15:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint16 *) temp->pixels) & 0x00007FFF);
break;
case 16:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels);
break;
case 24:
SDL_SetColorKey(temp, SDL_TRUE,
(*(Uint32 *) temp->pixels) & 0x00FFFFFF);
break;
case 32:
SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels);
break;
}
}
/* Create textures from the image */
sprite = SDL_CreateTextureFromSurface(renderer, temp);
if (!sprite) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError());
SDL_FreeSurface(temp);
return (-1);
}
SDL_FreeSurface(temp);
/* We're ready to roll. :) */
return (0);
}
void
DrawOnViewport(SDL_Renderer * renderer, SDL_Rect viewport)
{
SDL_Rect rect;
/* Set the viewport */
SDL_RenderSetViewport(renderer, &viewport);
/* Draw a gray background */
SDL_SetRenderDrawColor(renderer, 0x80, 0x80, 0x80, 0xFF);
SDL_RenderClear(renderer);
/* Test inside points */
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0x00, 0xFF);
SDL_RenderDrawPoint(renderer, viewport.h/2 + 20, viewport.w/2);
SDL_RenderDrawPoint(renderer, viewport.h/2 - 20, viewport.w/2);
SDL_RenderDrawPoint(renderer, viewport.h/2 , viewport.w/2 - 20);
SDL_RenderDrawPoint(renderer, viewport.h/2 , viewport.w/2 + 20);
/* Test horizontal and vertical lines */
SDL_SetRenderDrawColor(renderer, 0x00, 0xFF, 0x00, 0xFF);
SDL_RenderDrawLine(renderer, 1, 0, viewport.w-2, 0);
SDL_RenderDrawLine(renderer, 1, viewport.h-1, viewport.w-2, viewport.h-1);
SDL_RenderDrawLine(renderer, 0, 1, 0, viewport.h-2);
SDL_RenderDrawLine(renderer, viewport.w-1, 1, viewport.w-1, viewport.h-2);
/* Test diagonal lines */
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0xFF, 0xFF);
SDL_RenderDrawLine(renderer, 0, 0, viewport.w-1, viewport.h-1);
SDL_RenderDrawLine(renderer, viewport.w-1, 0, 0, viewport.h-1);
/* Test outside points */
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0x00, 0xFF);
SDL_RenderDrawPoint(renderer, viewport.h/2 + viewport.h, viewport.w/2);
SDL_RenderDrawPoint(renderer, viewport.h/2 - viewport.h, viewport.w/2);
SDL_RenderDrawPoint(renderer, viewport.h/2, viewport.w/2 - viewport.w);
SDL_RenderDrawPoint(renderer, viewport.h/2, viewport.w/2 + viewport.w);
/* Add a box at the top */
rect.w = 8;
rect.h = 8;
rect.x = (viewport.w - rect.w) / 2;
rect.y = 0;
SDL_RenderFillRect(renderer, &rect);
/* Add a clip rect and fill it with the sprite */
SDL_QueryTexture(sprite, NULL, NULL, &rect.w, &rect.h);
rect.x = (viewport.w - rect.w) / 2;
rect.y = (viewport.h - rect.h) / 2;
SDL_RenderSetClipRect(renderer, &rect);
SDL_RenderCopy(renderer, sprite, NULL, &rect);
SDL_RenderSetClipRect(renderer, NULL);
}
void
loop()
{
#ifdef __EMSCRIPTEN__
/* Avoid using delays */
if(SDL_GetTicks() - wait_start < 1000)
return;
wait_start = SDL_GetTicks();
#endif
SDL_Event event;
int i;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
}
/* Move a viewport box in steps around the screen */
viewport.x = j * 100;
viewport.y = viewport.x;
viewport.w = 100 + j * 50;
viewport.h = 100 + j * 50;
j = (j + 1) % 4;
SDL_Log("Current Viewport x=%i y=%i w=%i h=%i", viewport.x, viewport.y, viewport.w, viewport.h);
for (i = 0; i < state->num_windows; ++i) {
if (state->windows[i] == NULL)
continue;
/* Draw using viewport */
DrawOnViewport(state->renderers[i], viewport);
/* Update the screen! */
if (use_target) {
SDL_SetRenderTarget(state->renderers[i], NULL);
SDL_RenderCopy(state->renderers[i], state->targets[i], NULL, NULL);
SDL_RenderPresent(state->renderers[i]);
SDL_SetRenderTarget(state->renderers[i], state->targets[i]);
} else {
SDL_RenderPresent(state->renderers[i]);
}
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
Uint32 then, now, frames;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
for (i = 1; i < argc;) {
int consumed;
consumed = SDLTest_CommonArg(state, i);
if (consumed == 0) {
consumed = -1;
if (SDL_strcasecmp(argv[i], "--target") == 0) {
use_target = SDL_TRUE;
consumed = 1;
}
}
if (consumed < 0) {
static const char *options[] = { "[--target]", NULL };
SDLTest_CommonLogUsage(state, argv[0], options);
quit(1);
}
i += consumed;
}
if (!SDLTest_CommonInit(state)) {
quit(2);
}
if (LoadSprite("icon.bmp", state->renderers[0]) < 0) {
quit(2);
}
if (use_target) {
int w, h;
for (i = 0; i < state->num_windows; ++i) {
SDL_GetWindowSize(state->windows[i], &w, &h);
state->targets[i] = SDL_CreateTexture(state->renderers[i], SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, w, h);
SDL_SetRenderTarget(state->renderers[i], state->targets[i]);
}
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
j = 0;
#ifdef __EMSCRIPTEN__
wait_start = SDL_GetTicks();
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
++frames;
loop();
SDL_Delay(1000);
}
#endif
/* Print out some timing information */
now = SDL_GetTicks();
if (now > then) {
double fps = ((double) frames * 1000) / (now - then);
SDL_Log("%2.2f frames per second\n", fps);
}
quit(0);
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testviewport.c | C | apache-2.0 | 7,997 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "SDL_test_common.h"
#if defined(__ANDROID__) && defined(__ARM_EABI__) && !defined(__ARM_ARCH_7A__)
int main(int argc, char *argv[])
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "No Vulkan support on this system\n");
return 1;
}
#else
#define VK_NO_PROTOTYPES
#ifdef HAVE_VULKAN_H
#include <vulkan/vulkan.h>
#else
/* SDL includes a copy for building on systems without the Vulkan SDK */
#include "../src/video/khronos/vulkan/vulkan.h"
#endif
#include "SDL_vulkan.h"
#ifndef UINT64_MAX /* VS2008 */
#define UINT64_MAX 18446744073709551615
#endif
#define VULKAN_FUNCTIONS() \
VULKAN_DEVICE_FUNCTION(vkAcquireNextImageKHR) \
VULKAN_DEVICE_FUNCTION(vkAllocateCommandBuffers) \
VULKAN_DEVICE_FUNCTION(vkBeginCommandBuffer) \
VULKAN_DEVICE_FUNCTION(vkCmdClearColorImage) \
VULKAN_DEVICE_FUNCTION(vkCmdPipelineBarrier) \
VULKAN_DEVICE_FUNCTION(vkCreateCommandPool) \
VULKAN_DEVICE_FUNCTION(vkCreateFence) \
VULKAN_DEVICE_FUNCTION(vkCreateImageView) \
VULKAN_DEVICE_FUNCTION(vkCreateSemaphore) \
VULKAN_DEVICE_FUNCTION(vkCreateSwapchainKHR) \
VULKAN_DEVICE_FUNCTION(vkDestroyCommandPool) \
VULKAN_DEVICE_FUNCTION(vkDestroyDevice) \
VULKAN_DEVICE_FUNCTION(vkDestroyFence) \
VULKAN_DEVICE_FUNCTION(vkDestroyImageView) \
VULKAN_DEVICE_FUNCTION(vkDestroySemaphore) \
VULKAN_DEVICE_FUNCTION(vkDestroySwapchainKHR) \
VULKAN_DEVICE_FUNCTION(vkDeviceWaitIdle) \
VULKAN_DEVICE_FUNCTION(vkEndCommandBuffer) \
VULKAN_DEVICE_FUNCTION(vkFreeCommandBuffers) \
VULKAN_DEVICE_FUNCTION(vkGetDeviceQueue) \
VULKAN_DEVICE_FUNCTION(vkGetFenceStatus) \
VULKAN_DEVICE_FUNCTION(vkGetSwapchainImagesKHR) \
VULKAN_DEVICE_FUNCTION(vkQueuePresentKHR) \
VULKAN_DEVICE_FUNCTION(vkQueueSubmit) \
VULKAN_DEVICE_FUNCTION(vkResetCommandBuffer) \
VULKAN_DEVICE_FUNCTION(vkResetFences) \
VULKAN_DEVICE_FUNCTION(vkWaitForFences) \
VULKAN_GLOBAL_FUNCTION(vkCreateInstance) \
VULKAN_GLOBAL_FUNCTION(vkEnumerateInstanceExtensionProperties) \
VULKAN_GLOBAL_FUNCTION(vkEnumerateInstanceLayerProperties) \
VULKAN_INSTANCE_FUNCTION(vkCreateDevice) \
VULKAN_INSTANCE_FUNCTION(vkDestroyInstance) \
VULKAN_INSTANCE_FUNCTION(vkDestroySurfaceKHR) \
VULKAN_INSTANCE_FUNCTION(vkEnumerateDeviceExtensionProperties) \
VULKAN_INSTANCE_FUNCTION(vkEnumeratePhysicalDevices) \
VULKAN_INSTANCE_FUNCTION(vkGetDeviceProcAddr) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceFeatures) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceProperties) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceQueueFamilyProperties) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceFormatsKHR) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfacePresentModesKHR) \
VULKAN_INSTANCE_FUNCTION(vkGetPhysicalDeviceSurfaceSupportKHR)
#define VULKAN_DEVICE_FUNCTION(name) static PFN_##name name = NULL;
#define VULKAN_GLOBAL_FUNCTION(name) static PFN_##name name = NULL;
#define VULKAN_INSTANCE_FUNCTION(name) static PFN_##name name = NULL;
VULKAN_FUNCTIONS()
#undef VULKAN_DEVICE_FUNCTION
#undef VULKAN_GLOBAL_FUNCTION
#undef VULKAN_INSTANCE_FUNCTION
static PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = NULL;
/* Based on the headers found in
* https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers
*/
#if VK_HEADER_VERSION < 22
enum
{
VK_ERROR_FRAGMENTED_POOL = -12,
};
#endif
#if VK_HEADER_VERSION < 38
enum {
VK_ERROR_OUT_OF_POOL_MEMORY_KHR = -1000069000
};
#endif
static const char *getVulkanResultString(VkResult result)
{
switch((int)result)
{
case VK_SUCCESS:
return "VK_SUCCESS";
case VK_NOT_READY:
return "VK_NOT_READY";
case VK_TIMEOUT:
return "VK_TIMEOUT";
case VK_EVENT_SET:
return "VK_EVENT_SET";
case VK_EVENT_RESET:
return "VK_EVENT_RESET";
case VK_INCOMPLETE:
return "VK_INCOMPLETE";
case VK_ERROR_OUT_OF_HOST_MEMORY:
return "VK_ERROR_OUT_OF_HOST_MEMORY";
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
return "VK_ERROR_OUT_OF_DEVICE_MEMORY";
case VK_ERROR_INITIALIZATION_FAILED:
return "VK_ERROR_INITIALIZATION_FAILED";
case VK_ERROR_DEVICE_LOST:
return "VK_ERROR_DEVICE_LOST";
case VK_ERROR_MEMORY_MAP_FAILED:
return "VK_ERROR_MEMORY_MAP_FAILED";
case VK_ERROR_LAYER_NOT_PRESENT:
return "VK_ERROR_LAYER_NOT_PRESENT";
case VK_ERROR_EXTENSION_NOT_PRESENT:
return "VK_ERROR_EXTENSION_NOT_PRESENT";
case VK_ERROR_FEATURE_NOT_PRESENT:
return "VK_ERROR_FEATURE_NOT_PRESENT";
case VK_ERROR_INCOMPATIBLE_DRIVER:
return "VK_ERROR_INCOMPATIBLE_DRIVER";
case VK_ERROR_TOO_MANY_OBJECTS:
return "VK_ERROR_TOO_MANY_OBJECTS";
case VK_ERROR_FORMAT_NOT_SUPPORTED:
return "VK_ERROR_FORMAT_NOT_SUPPORTED";
case VK_ERROR_FRAGMENTED_POOL:
return "VK_ERROR_FRAGMENTED_POOL";
case VK_ERROR_SURFACE_LOST_KHR:
return "VK_ERROR_SURFACE_LOST_KHR";
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
return "VK_ERROR_NATIVE_WINDOW_IN_USE_KHR";
case VK_SUBOPTIMAL_KHR:
return "VK_SUBOPTIMAL_KHR";
case VK_ERROR_OUT_OF_DATE_KHR:
return "VK_ERROR_OUT_OF_DATE_KHR";
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
return "VK_ERROR_INCOMPATIBLE_DISPLAY_KHR";
case VK_ERROR_VALIDATION_FAILED_EXT:
return "VK_ERROR_VALIDATION_FAILED_EXT";
case VK_ERROR_OUT_OF_POOL_MEMORY_KHR:
return "VK_ERROR_OUT_OF_POOL_MEMORY_KHR";
case VK_ERROR_INVALID_SHADER_NV:
return "VK_ERROR_INVALID_SHADER_NV";
case VK_RESULT_MAX_ENUM:
case VK_RESULT_RANGE_SIZE:
break;
}
if(result < 0)
return "VK_ERROR_<Unknown>";
return "VK_<Unknown>";
}
typedef struct VulkanContext
{
VkInstance instance;
VkDevice device;
VkSurfaceKHR surface;
VkSwapchainKHR swapchain;
VkPhysicalDeviceProperties physicalDeviceProperties;
VkPhysicalDeviceFeatures physicalDeviceFeatures;
uint32_t graphicsQueueFamilyIndex;
uint32_t presentQueueFamilyIndex;
VkPhysicalDevice physicalDevice;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkSemaphore imageAvailableSemaphore;
VkSemaphore renderingFinishedSemaphore;
VkSurfaceCapabilitiesKHR surfaceCapabilities;
VkSurfaceFormatKHR *surfaceFormats;
uint32_t surfaceFormatsAllocatedCount;
uint32_t surfaceFormatsCount;
uint32_t swapchainDesiredImageCount;
VkSurfaceFormatKHR surfaceFormat;
VkExtent2D swapchainSize;
VkCommandPool commandPool;
uint32_t swapchainImageCount;
VkImage *swapchainImages;
VkCommandBuffer *commandBuffers;
VkFence *fences;
} VulkanContext;
static SDLTest_CommonState *state;
static VulkanContext vulkanContext = {0};
static void shutdownVulkan(void);
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void quit(int rc)
{
shutdownVulkan();
SDLTest_CommonQuit(state);
exit(rc);
}
static void loadGlobalFunctions(void)
{
vkGetInstanceProcAddr = SDL_Vulkan_GetVkGetInstanceProcAddr();
if(!vkGetInstanceProcAddr)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_Vulkan_GetVkGetInstanceProcAddr(): %s\n",
SDL_GetError());
quit(2);
}
#define VULKAN_DEVICE_FUNCTION(name)
#define VULKAN_GLOBAL_FUNCTION(name) \
name = (PFN_##name)vkGetInstanceProcAddr(VK_NULL_HANDLE, #name); \
if(!name) \
{ \
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, \
"vkGetInstanceProcAddr(VK_NULL_HANDLE, \"" #name "\") failed\n"); \
quit(2); \
}
#define VULKAN_INSTANCE_FUNCTION(name)
VULKAN_FUNCTIONS()
#undef VULKAN_DEVICE_FUNCTION
#undef VULKAN_GLOBAL_FUNCTION
#undef VULKAN_INSTANCE_FUNCTION
}
static void createInstance(void)
{
VkApplicationInfo appInfo = {0};
VkInstanceCreateInfo instanceCreateInfo = {0};
const char **extensions = NULL;
unsigned extensionCount = 0;
VkResult result;
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.apiVersion = VK_API_VERSION_1_0;
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pApplicationInfo = &appInfo;
if(!SDL_Vulkan_GetInstanceExtensions(NULL, &extensionCount, NULL))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_Vulkan_GetInstanceExtensions(): %s\n",
SDL_GetError());
quit(2);
}
extensions = SDL_malloc(sizeof(const char *) * extensionCount);
if(!extensions)
{
SDL_OutOfMemory();
quit(2);
}
if(!SDL_Vulkan_GetInstanceExtensions(NULL, &extensionCount, extensions))
{
SDL_free((void*)extensions);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"SDL_Vulkan_GetInstanceExtensions(): %s\n",
SDL_GetError());
quit(2);
}
instanceCreateInfo.enabledExtensionCount = extensionCount;
instanceCreateInfo.ppEnabledExtensionNames = extensions;
result = vkCreateInstance(&instanceCreateInfo, NULL, &vulkanContext.instance);
SDL_free((void*)extensions);
if(result != VK_SUCCESS)
{
vulkanContext.instance = VK_NULL_HANDLE;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkCreateInstance(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static void loadInstanceFunctions(void)
{
#define VULKAN_DEVICE_FUNCTION(name)
#define VULKAN_GLOBAL_FUNCTION(name)
#define VULKAN_INSTANCE_FUNCTION(name) \
name = (PFN_##name)vkGetInstanceProcAddr(vulkanContext.instance, #name); \
if(!name) \
{ \
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, \
"vkGetInstanceProcAddr(instance, \"" #name "\") failed\n"); \
quit(2); \
}
VULKAN_FUNCTIONS()
#undef VULKAN_DEVICE_FUNCTION
#undef VULKAN_GLOBAL_FUNCTION
#undef VULKAN_INSTANCE_FUNCTION
}
static void createSurface(void)
{
if(!SDL_Vulkan_CreateSurface(state->windows[0],
vulkanContext.instance,
&vulkanContext.surface))
{
vulkanContext.surface = VK_NULL_HANDLE;
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION, "SDL_Vulkan_CreateSurface(): %s\n", SDL_GetError());
quit(2);
}
}
static void findPhysicalDevice(void)
{
uint32_t physicalDeviceCount = 0;
VkPhysicalDevice *physicalDevices;
VkQueueFamilyProperties *queueFamiliesProperties = NULL;
uint32_t queueFamiliesPropertiesAllocatedSize = 0;
VkExtensionProperties *deviceExtensions = NULL;
uint32_t deviceExtensionsAllocatedSize = 0;
uint32_t physicalDeviceIndex;
VkResult result =
vkEnumeratePhysicalDevices(vulkanContext.instance, &physicalDeviceCount, NULL);
if(result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkEnumeratePhysicalDevices(): %s\n",
getVulkanResultString(result));
quit(2);
}
if(physicalDeviceCount == 0)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkEnumeratePhysicalDevices(): no physical devices\n");
quit(2);
}
physicalDevices = SDL_malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
if(!physicalDevices)
{
SDL_OutOfMemory();
quit(2);
}
result =
vkEnumeratePhysicalDevices(vulkanContext.instance, &physicalDeviceCount, physicalDevices);
if(result != VK_SUCCESS)
{
SDL_free(physicalDevices);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkEnumeratePhysicalDevices(): %s\n",
getVulkanResultString(result));
quit(2);
}
vulkanContext.physicalDevice = NULL;
for(physicalDeviceIndex = 0; physicalDeviceIndex < physicalDeviceCount;
physicalDeviceIndex++)
{
uint32_t queueFamiliesCount = 0;
uint32_t queueFamilyIndex;
uint32_t deviceExtensionCount = 0;
SDL_bool hasSwapchainExtension = SDL_FALSE;
uint32_t i;
VkPhysicalDevice physicalDevice = physicalDevices[physicalDeviceIndex];
vkGetPhysicalDeviceProperties(physicalDevice, &vulkanContext.physicalDeviceProperties);
if(VK_VERSION_MAJOR(vulkanContext.physicalDeviceProperties.apiVersion) < 1)
continue;
vkGetPhysicalDeviceFeatures(physicalDevice, &vulkanContext.physicalDeviceFeatures);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamiliesCount, NULL);
if(queueFamiliesCount == 0)
continue;
if(queueFamiliesPropertiesAllocatedSize < queueFamiliesCount)
{
SDL_free(queueFamiliesProperties);
queueFamiliesPropertiesAllocatedSize = queueFamiliesCount;
queueFamiliesProperties =
SDL_malloc(sizeof(VkQueueFamilyProperties) * queueFamiliesPropertiesAllocatedSize);
if(!queueFamiliesProperties)
{
SDL_free(physicalDevices);
SDL_free(deviceExtensions);
SDL_OutOfMemory();
quit(2);
}
}
vkGetPhysicalDeviceQueueFamilyProperties(
physicalDevice, &queueFamiliesCount, queueFamiliesProperties);
vulkanContext.graphicsQueueFamilyIndex = queueFamiliesCount;
vulkanContext.presentQueueFamilyIndex = queueFamiliesCount;
for(queueFamilyIndex = 0; queueFamilyIndex < queueFamiliesCount;
queueFamilyIndex++)
{
VkBool32 supported = 0;
if(queueFamiliesProperties[queueFamilyIndex].queueCount == 0)
continue;
if(queueFamiliesProperties[queueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
vulkanContext.graphicsQueueFamilyIndex = queueFamilyIndex;
result = vkGetPhysicalDeviceSurfaceSupportKHR(
physicalDevice, queueFamilyIndex, vulkanContext.surface, &supported);
if(result != VK_SUCCESS)
{
SDL_free(physicalDevices);
SDL_free(queueFamiliesProperties);
SDL_free(deviceExtensions);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkGetPhysicalDeviceSurfaceSupportKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
if(supported)
{
vulkanContext.presentQueueFamilyIndex = queueFamilyIndex;
if(queueFamiliesProperties[queueFamilyIndex].queueFlags & VK_QUEUE_GRAPHICS_BIT)
break; // use this queue because it can present and do graphics
}
}
if(vulkanContext.graphicsQueueFamilyIndex == queueFamiliesCount) // no good queues found
continue;
if(vulkanContext.presentQueueFamilyIndex == queueFamiliesCount) // no good queues found
continue;
result =
vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &deviceExtensionCount, NULL);
if(result != VK_SUCCESS)
{
SDL_free(physicalDevices);
SDL_free(queueFamiliesProperties);
SDL_free(deviceExtensions);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkEnumerateDeviceExtensionProperties(): %s\n",
getVulkanResultString(result));
quit(2);
}
if(deviceExtensionCount == 0)
continue;
if(deviceExtensionsAllocatedSize < deviceExtensionCount)
{
SDL_free(deviceExtensions);
deviceExtensionsAllocatedSize = deviceExtensionCount;
deviceExtensions =
SDL_malloc(sizeof(VkExtensionProperties) * deviceExtensionsAllocatedSize);
if(!deviceExtensions)
{
SDL_free(physicalDevices);
SDL_free(queueFamiliesProperties);
SDL_OutOfMemory();
quit(2);
}
}
result = vkEnumerateDeviceExtensionProperties(
physicalDevice, NULL, &deviceExtensionCount, deviceExtensions);
if(result != VK_SUCCESS)
{
SDL_free(physicalDevices);
SDL_free(queueFamiliesProperties);
SDL_free(deviceExtensions);
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkEnumerateDeviceExtensionProperties(): %s\n",
getVulkanResultString(result));
quit(2);
}
for(i = 0; i < deviceExtensionCount; i++)
{
if(0 == SDL_strcmp(deviceExtensions[i].extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME))
{
hasSwapchainExtension = SDL_TRUE;
break;
}
}
if(!hasSwapchainExtension)
continue;
vulkanContext.physicalDevice = physicalDevice;
break;
}
SDL_free(physicalDevices);
SDL_free(queueFamiliesProperties);
SDL_free(deviceExtensions);
if(!vulkanContext.physicalDevice)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vulkan: no viable physical devices found");
quit(2);
}
}
static void createDevice(void)
{
VkDeviceQueueCreateInfo deviceQueueCreateInfo[1] = {0};
static const float queuePriority[] = {1.0f};
VkDeviceCreateInfo deviceCreateInfo = {0};
static const char *const deviceExtensionNames[] = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
};
VkResult result;
deviceQueueCreateInfo->sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
deviceQueueCreateInfo->queueFamilyIndex = vulkanContext.graphicsQueueFamilyIndex;
deviceQueueCreateInfo->queueCount = 1;
deviceQueueCreateInfo->pQueuePriorities = &queuePriority[0];
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfo;
deviceCreateInfo.pEnabledFeatures = NULL;
deviceCreateInfo.enabledExtensionCount = SDL_arraysize(deviceExtensionNames);
deviceCreateInfo.ppEnabledExtensionNames = deviceExtensionNames;
result = vkCreateDevice(
vulkanContext.physicalDevice, &deviceCreateInfo, NULL, &vulkanContext.device);
if(result != VK_SUCCESS)
{
vulkanContext.device = VK_NULL_HANDLE;
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION, "vkCreateDevice(): %s\n", getVulkanResultString(result));
quit(2);
}
}
static void loadDeviceFunctions(void)
{
#define VULKAN_DEVICE_FUNCTION(name) \
name = (PFN_##name)vkGetDeviceProcAddr(vulkanContext.device, #name); \
if(!name) \
{ \
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, \
"vkGetDeviceProcAddr(device, \"" #name "\") failed\n"); \
quit(2); \
}
#define VULKAN_GLOBAL_FUNCTION(name)
#define VULKAN_INSTANCE_FUNCTION(name)
VULKAN_FUNCTIONS()
#undef VULKAN_DEVICE_FUNCTION
#undef VULKAN_GLOBAL_FUNCTION
#undef VULKAN_INSTANCE_FUNCTION
}
#undef VULKAN_FUNCTIONS
static void getQueues(void)
{
vkGetDeviceQueue(vulkanContext.device,
vulkanContext.graphicsQueueFamilyIndex,
0,
&vulkanContext.graphicsQueue);
if(vulkanContext.graphicsQueueFamilyIndex != vulkanContext.presentQueueFamilyIndex)
vkGetDeviceQueue(vulkanContext.device,
vulkanContext.presentQueueFamilyIndex,
0,
&vulkanContext.presentQueue);
else
vulkanContext.presentQueue = vulkanContext.graphicsQueue;
}
static void createSemaphore(VkSemaphore *semaphore)
{
VkResult result;
VkSemaphoreCreateInfo createInfo = {0};
createInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
result = vkCreateSemaphore(vulkanContext.device, &createInfo, NULL, semaphore);
if(result != VK_SUCCESS)
{
*semaphore = VK_NULL_HANDLE;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkCreateSemaphore(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static void createSemaphores(void)
{
createSemaphore(&vulkanContext.imageAvailableSemaphore);
createSemaphore(&vulkanContext.renderingFinishedSemaphore);
}
static void getSurfaceCaps(void)
{
VkResult result = vkGetPhysicalDeviceSurfaceCapabilitiesKHR(
vulkanContext.physicalDevice, vulkanContext.surface, &vulkanContext.surfaceCapabilities);
if(result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkGetPhysicalDeviceSurfaceCapabilitiesKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
// check surface usage
if(!(vulkanContext.surfaceCapabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_DST_BIT))
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"Vulkan surface doesn't support VK_IMAGE_USAGE_TRANSFER_DST_BIT\n");
quit(2);
}
}
static void getSurfaceFormats(void)
{
VkResult result = vkGetPhysicalDeviceSurfaceFormatsKHR(vulkanContext.physicalDevice,
vulkanContext.surface,
&vulkanContext.surfaceFormatsCount,
NULL);
if(result != VK_SUCCESS)
{
vulkanContext.surfaceFormatsCount = 0;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkGetPhysicalDeviceSurfaceFormatsKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
if(vulkanContext.surfaceFormatsCount > vulkanContext.surfaceFormatsAllocatedCount)
{
vulkanContext.surfaceFormatsAllocatedCount = vulkanContext.surfaceFormatsCount;
SDL_free(vulkanContext.surfaceFormats);
vulkanContext.surfaceFormats =
SDL_malloc(sizeof(VkSurfaceFormatKHR) * vulkanContext.surfaceFormatsAllocatedCount);
if(!vulkanContext.surfaceFormats)
{
vulkanContext.surfaceFormatsCount = 0;
SDL_OutOfMemory();
quit(2);
}
}
result = vkGetPhysicalDeviceSurfaceFormatsKHR(vulkanContext.physicalDevice,
vulkanContext.surface,
&vulkanContext.surfaceFormatsCount,
vulkanContext.surfaceFormats);
if(result != VK_SUCCESS)
{
vulkanContext.surfaceFormatsCount = 0;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkGetPhysicalDeviceSurfaceFormatsKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static void getSwapchainImages(void)
{
VkResult result;
SDL_free(vulkanContext.swapchainImages);
vulkanContext.swapchainImages = NULL;
result = vkGetSwapchainImagesKHR(
vulkanContext.device, vulkanContext.swapchain, &vulkanContext.swapchainImageCount, NULL);
if(result != VK_SUCCESS)
{
vulkanContext.swapchainImageCount = 0;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkGetSwapchainImagesKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
vulkanContext.swapchainImages = SDL_malloc(sizeof(VkImage) * vulkanContext.swapchainImageCount);
if(!vulkanContext.swapchainImages)
{
SDL_OutOfMemory();
quit(2);
}
result = vkGetSwapchainImagesKHR(vulkanContext.device,
vulkanContext.swapchain,
&vulkanContext.swapchainImageCount,
vulkanContext.swapchainImages);
if(result != VK_SUCCESS)
{
SDL_free(vulkanContext.swapchainImages);
vulkanContext.swapchainImages = NULL;
vulkanContext.swapchainImageCount = 0;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkGetSwapchainImagesKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static SDL_bool createSwapchain(void)
{
uint32_t i;
int w, h;
VkSwapchainCreateInfoKHR createInfo = {0};
VkResult result;
// pick an image count
vulkanContext.swapchainDesiredImageCount = vulkanContext.surfaceCapabilities.minImageCount + 1;
if(vulkanContext.swapchainDesiredImageCount > vulkanContext.surfaceCapabilities.maxImageCount
&& vulkanContext.surfaceCapabilities.maxImageCount > 0)
vulkanContext.swapchainDesiredImageCount = vulkanContext.surfaceCapabilities.maxImageCount;
// pick a format
if(vulkanContext.surfaceFormatsCount == 1
&& vulkanContext.surfaceFormats[0].format == VK_FORMAT_UNDEFINED)
{
// aren't any preferred formats, so we pick
vulkanContext.surfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
vulkanContext.surfaceFormat.format = VK_FORMAT_R8G8B8A8_UNORM;
}
else
{
vulkanContext.surfaceFormat = vulkanContext.surfaceFormats[0];
for(i = 0; i < vulkanContext.surfaceFormatsCount; i++)
{
if(vulkanContext.surfaceFormats[i].format == VK_FORMAT_R8G8B8A8_UNORM)
{
vulkanContext.surfaceFormat = vulkanContext.surfaceFormats[i];
break;
}
}
}
// get size
SDL_Vulkan_GetDrawableSize(state->windows[0], &w, &h);
vulkanContext.swapchainSize.width = w;
vulkanContext.swapchainSize.height = h;
if(w == 0 || h == 0)
return SDL_FALSE;
createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
createInfo.surface = vulkanContext.surface;
createInfo.minImageCount = vulkanContext.swapchainDesiredImageCount;
createInfo.imageFormat = vulkanContext.surfaceFormat.format;
createInfo.imageColorSpace = vulkanContext.surfaceFormat.colorSpace;
createInfo.imageExtent = vulkanContext.swapchainSize;
createInfo.imageArrayLayers = 1;
createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.preTransform = vulkanContext.surfaceCapabilities.currentTransform;
createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
createInfo.presentMode = VK_PRESENT_MODE_FIFO_KHR;
createInfo.clipped = VK_TRUE;
createInfo.oldSwapchain = vulkanContext.swapchain;
result =
vkCreateSwapchainKHR(vulkanContext.device, &createInfo, NULL, &vulkanContext.swapchain);
if(createInfo.oldSwapchain)
vkDestroySwapchainKHR(vulkanContext.device, createInfo.oldSwapchain, NULL);
if(result != VK_SUCCESS)
{
vulkanContext.swapchain = VK_NULL_HANDLE;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkCreateSwapchainKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
getSwapchainImages();
return SDL_TRUE;
}
static void destroySwapchain(void)
{
if(vulkanContext.swapchain)
vkDestroySwapchainKHR(vulkanContext.device, vulkanContext.swapchain, NULL);
vulkanContext.swapchain = VK_NULL_HANDLE;
SDL_free(vulkanContext.swapchainImages);
vulkanContext.swapchainImages = NULL;
}
static void destroyCommandBuffers(void)
{
if(vulkanContext.commandBuffers)
vkFreeCommandBuffers(vulkanContext.device,
vulkanContext.commandPool,
vulkanContext.swapchainImageCount,
vulkanContext.commandBuffers);
SDL_free(vulkanContext.commandBuffers);
vulkanContext.commandBuffers = NULL;
}
static void destroyCommandPool(void)
{
if(vulkanContext.commandPool)
vkDestroyCommandPool(vulkanContext.device, vulkanContext.commandPool, NULL);
vulkanContext.commandPool = VK_NULL_HANDLE;
}
static void createCommandPool(void)
{
VkResult result;
VkCommandPoolCreateInfo createInfo = {0};
createInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
createInfo.flags =
VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
createInfo.queueFamilyIndex = vulkanContext.graphicsQueueFamilyIndex;
result =
vkCreateCommandPool(vulkanContext.device, &createInfo, NULL, &vulkanContext.commandPool);
if(result != VK_SUCCESS)
{
vulkanContext.commandPool = VK_NULL_HANDLE;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkCreateCommandPool(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static void createCommandBuffers(void)
{
VkResult result;
VkCommandBufferAllocateInfo allocateInfo = {0};
allocateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocateInfo.commandPool = vulkanContext.commandPool;
allocateInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocateInfo.commandBufferCount = vulkanContext.swapchainImageCount;
vulkanContext.commandBuffers =
SDL_malloc(sizeof(VkCommandBuffer) * vulkanContext.swapchainImageCount);
result =
vkAllocateCommandBuffers(vulkanContext.device, &allocateInfo, vulkanContext.commandBuffers);
if(result != VK_SUCCESS)
{
SDL_free(vulkanContext.commandBuffers);
vulkanContext.commandBuffers = NULL;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkAllocateCommandBuffers(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static void createFences(void)
{
uint32_t i;
vulkanContext.fences = SDL_malloc(sizeof(VkFence) * vulkanContext.swapchainImageCount);
if(!vulkanContext.fences)
{
SDL_OutOfMemory();
quit(2);
}
for(i = 0; i < vulkanContext.swapchainImageCount; i++)
{
VkResult result;
VkFenceCreateInfo createInfo = {0};
createInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
createInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
result =
vkCreateFence(vulkanContext.device, &createInfo, NULL, &vulkanContext.fences[i]);
if(result != VK_SUCCESS)
{
for(; i > 0; i--)
{
vkDestroyFence(vulkanContext.device, vulkanContext.fences[i - 1], NULL);
}
SDL_free(vulkanContext.fences);
vulkanContext.fences = NULL;
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkCreateFence(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
}
static void destroyFences(void)
{
uint32_t i;
if(!vulkanContext.fences)
return;
for(i = 0; i < vulkanContext.swapchainImageCount; i++)
{
vkDestroyFence(vulkanContext.device, vulkanContext.fences[i], NULL);
}
SDL_free(vulkanContext.fences);
vulkanContext.fences = NULL;
}
static void recordPipelineImageBarrier(VkCommandBuffer commandBuffer,
VkAccessFlags sourceAccessMask,
VkAccessFlags destAccessMask,
VkImageLayout sourceLayout,
VkImageLayout destLayout,
VkImage image)
{
VkImageMemoryBarrier barrier = {0};
barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
barrier.srcAccessMask = sourceAccessMask;
barrier.dstAccessMask = destAccessMask;
barrier.oldLayout = sourceLayout;
barrier.newLayout = destLayout;
barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
barrier.image = image;
barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
barrier.subresourceRange.baseMipLevel = 0;
barrier.subresourceRange.levelCount = 1;
barrier.subresourceRange.baseArrayLayer = 0;
barrier.subresourceRange.layerCount = 1;
vkCmdPipelineBarrier(commandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT,
0,
0,
NULL,
0,
NULL,
1,
&barrier);
}
static void rerecordCommandBuffer(uint32_t frameIndex, const VkClearColorValue *clearColor)
{
VkCommandBuffer commandBuffer = vulkanContext.commandBuffers[frameIndex];
VkImage image = vulkanContext.swapchainImages[frameIndex];
VkCommandBufferBeginInfo beginInfo = {0};
VkImageSubresourceRange clearRange = {0};
VkResult result = vkResetCommandBuffer(commandBuffer, 0);
if(result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkResetCommandBuffer(): %s\n",
getVulkanResultString(result));
quit(2);
}
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
result = vkBeginCommandBuffer(commandBuffer, &beginInfo);
if(result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkBeginCommandBuffer(): %s\n",
getVulkanResultString(result));
quit(2);
}
recordPipelineImageBarrier(commandBuffer,
0,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
image);
clearRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
clearRange.baseMipLevel = 0;
clearRange.levelCount = 1;
clearRange.baseArrayLayer = 0;
clearRange.layerCount = 1;
vkCmdClearColorImage(
commandBuffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, clearColor, 1, &clearRange);
recordPipelineImageBarrier(commandBuffer,
VK_ACCESS_TRANSFER_WRITE_BIT,
VK_ACCESS_MEMORY_READ_BIT,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR,
image);
result = vkEndCommandBuffer(commandBuffer);
if(result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkEndCommandBuffer(): %s\n",
getVulkanResultString(result));
quit(2);
}
}
static void destroySwapchainAndSwapchainSpecificStuff(SDL_bool doDestroySwapchain)
{
destroyFences();
destroyCommandBuffers();
destroyCommandPool();
if(doDestroySwapchain)
destroySwapchain();
}
static SDL_bool createNewSwapchainAndSwapchainSpecificStuff(void)
{
destroySwapchainAndSwapchainSpecificStuff(SDL_FALSE);
getSurfaceCaps();
getSurfaceFormats();
if(!createSwapchain())
return SDL_FALSE;
createCommandPool();
createCommandBuffers();
createFences();
return SDL_TRUE;
}
static void initVulkan(void)
{
SDL_Vulkan_LoadLibrary(NULL);
SDL_memset(&vulkanContext, 0, sizeof(VulkanContext));
loadGlobalFunctions();
createInstance();
loadInstanceFunctions();
createSurface();
findPhysicalDevice();
createDevice();
loadDeviceFunctions();
getQueues();
createSemaphores();
createNewSwapchainAndSwapchainSpecificStuff();
}
static void shutdownVulkan(void)
{
if(vulkanContext.device && vkDeviceWaitIdle)
vkDeviceWaitIdle(vulkanContext.device);
destroySwapchainAndSwapchainSpecificStuff(SDL_TRUE);
if(vulkanContext.imageAvailableSemaphore && vkDestroySemaphore)
vkDestroySemaphore(vulkanContext.device, vulkanContext.imageAvailableSemaphore, NULL);
if(vulkanContext.renderingFinishedSemaphore && vkDestroySemaphore)
vkDestroySemaphore(vulkanContext.device, vulkanContext.renderingFinishedSemaphore, NULL);
if(vulkanContext.device && vkDestroyDevice)
vkDestroyDevice(vulkanContext.device, NULL);
if(vulkanContext.surface && vkDestroySurfaceKHR)
vkDestroySurfaceKHR(vulkanContext.instance, vulkanContext.surface, NULL);
if(vulkanContext.instance && vkDestroyInstance)
vkDestroyInstance(vulkanContext.instance, NULL);
SDL_free(vulkanContext.surfaceFormats);
SDL_Vulkan_UnloadLibrary();
}
static SDL_bool render(void)
{
uint32_t frameIndex;
VkResult result;
double currentTime;
VkClearColorValue clearColor = {0};
VkPipelineStageFlags waitDestStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
VkSubmitInfo submitInfo = {0};
VkPresentInfoKHR presentInfo = {0};
int w, h;
if(!vulkanContext.swapchain)
{
SDL_bool retval = createNewSwapchainAndSwapchainSpecificStuff();
if(!retval)
SDL_Delay(100);
return retval;
}
result = vkAcquireNextImageKHR(vulkanContext.device,
vulkanContext.swapchain,
UINT64_MAX,
vulkanContext.imageAvailableSemaphore,
VK_NULL_HANDLE,
&frameIndex);
if(result == VK_ERROR_OUT_OF_DATE_KHR)
return createNewSwapchainAndSwapchainSpecificStuff();
if(result != VK_SUBOPTIMAL_KHR && result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkAcquireNextImageKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
result = vkWaitForFences(
vulkanContext.device, 1, &vulkanContext.fences[frameIndex], VK_FALSE, UINT64_MAX);
if(result != VK_SUCCESS)
{
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION, "vkWaitForFences(): %s\n", getVulkanResultString(result));
quit(2);
}
result = vkResetFences(vulkanContext.device, 1, &vulkanContext.fences[frameIndex]);
if(result != VK_SUCCESS)
{
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION, "vkResetFences(): %s\n", getVulkanResultString(result));
quit(2);
}
currentTime = (double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency();
clearColor.float32[0] = (float)(0.5 + 0.5 * SDL_sin(currentTime));
clearColor.float32[1] = (float)(0.5 + 0.5 * SDL_sin(currentTime + M_PI * 2 / 3));
clearColor.float32[2] = (float)(0.5 + 0.5 * SDL_sin(currentTime + M_PI * 4 / 3));
clearColor.float32[3] = 1;
rerecordCommandBuffer(frameIndex, &clearColor);
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = &vulkanContext.imageAvailableSemaphore;
submitInfo.pWaitDstStageMask = &waitDestStageMask;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &vulkanContext.commandBuffers[frameIndex];
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = &vulkanContext.renderingFinishedSemaphore;
result = vkQueueSubmit(
vulkanContext.graphicsQueue, 1, &submitInfo, vulkanContext.fences[frameIndex]);
if(result != VK_SUCCESS)
{
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION, "vkQueueSubmit(): %s\n", getVulkanResultString(result));
quit(2);
}
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = &vulkanContext.renderingFinishedSemaphore;
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = &vulkanContext.swapchain;
presentInfo.pImageIndices = &frameIndex;
result = vkQueuePresentKHR(vulkanContext.presentQueue, &presentInfo);
if(result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR)
{
return createNewSwapchainAndSwapchainSpecificStuff();
}
if(result != VK_SUCCESS)
{
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
"vkQueuePresentKHR(): %s\n",
getVulkanResultString(result));
quit(2);
}
SDL_Vulkan_GetDrawableSize(state->windows[0], &w, &h);
if(w != (int)vulkanContext.swapchainSize.width || h != (int)vulkanContext.swapchainSize.height)
{
return createNewSwapchainAndSwapchainSpecificStuff();
}
return SDL_TRUE;
}
int main(int argc, char *argv[])
{
int fsaa, accel;
int done;
SDL_DisplayMode mode;
SDL_Event event;
Uint32 then, now, frames;
int dw, dh;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Initialize parameters */
fsaa = 0;
accel = -1;
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if(!state)
{
return 1;
}
/* Set Vulkan parameters */
state->window_flags |= SDL_WINDOW_VULKAN;
state->num_windows = 1;
state->skip_renderer = 1;
if (!SDLTest_CommonDefaultArgs(state, argc, argv) || !SDLTest_CommonInit(state)) {
SDLTest_CommonQuit(state);
return 1;
}
SDL_GetCurrentDisplayMode(0, &mode);
SDL_Log("Screen BPP : %d\n", SDL_BITSPERPIXEL(mode.format));
SDL_GetWindowSize(state->windows[0], &dw, &dh);
SDL_Log("Window Size : %d,%d\n", dw, dh);
SDL_Vulkan_GetDrawableSize(state->windows[0], &dw, &dh);
SDL_Log("Draw Size : %d,%d\n", dw, dh);
SDL_Log("\n");
initVulkan();
/* Main render loop */
frames = 0;
then = SDL_GetTicks();
done = 0;
while(!done)
{
/* Check for events */
++frames;
while(SDL_PollEvent(&event))
{
SDLTest_CommonEvent(state, &event, &done);
}
if(!done)
render();
}
/* Print out some timing information */
now = SDL_GetTicks();
if(now > then)
{
SDL_Log("%2.2f frames per second\n", ((double)frames * 1000) / (now - then));
}
quit(0);
return 0;
}
#endif
| YifuLiu/AliOS-Things | components/SDL2/test/testvulkan.c | C | apache-2.0 | 44,617 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
#include "SDL_test_common.h"
static SDLTest_CommonState *state;
int done;
static const char *cursorNames[] = {
"arrow",
"ibeam",
"wait",
"crosshair",
"waitarrow",
"sizeNWSE",
"sizeNESW",
"sizeWE",
"sizeNS",
"sizeALL",
"NO",
"hand",
};
int system_cursor = -1;
SDL_Cursor *cursor = NULL;
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDLTest_CommonQuit(state);
exit(rc);
}
void
loop()
{
int i;
SDL_Event event;
/* Check for events */
while (SDL_PollEvent(&event)) {
SDLTest_CommonEvent(state, &event, &done);
if (event.type == SDL_WINDOWEVENT) {
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
SDL_Window *window = SDL_GetWindowFromID(event.window.windowID);
if (window) {
SDL_Log("Window %d resized to %dx%d\n",
event.window.windowID,
event.window.data1,
event.window.data2);
}
}
if (event.window.event == SDL_WINDOWEVENT_MOVED) {
SDL_Window *window = SDL_GetWindowFromID(event.window.windowID);
if (window) {
SDL_Log("Window %d moved to %d,%d (display %s)\n",
event.window.windowID,
event.window.data1,
event.window.data2,
SDL_GetDisplayName(SDL_GetWindowDisplayIndex(window)));
}
}
}
if (event.type == SDL_KEYUP) {
SDL_bool updateCursor = SDL_FALSE;
if (event.key.keysym.sym == SDLK_LEFT) {
--system_cursor;
if (system_cursor < 0) {
system_cursor = SDL_NUM_SYSTEM_CURSORS - 1;
}
updateCursor = SDL_TRUE;
} else if (event.key.keysym.sym == SDLK_RIGHT) {
++system_cursor;
if (system_cursor >= SDL_NUM_SYSTEM_CURSORS) {
system_cursor = 0;
}
updateCursor = SDL_TRUE;
}
if (updateCursor) {
SDL_Log("Changing cursor to \"%s\"", cursorNames[system_cursor]);
SDL_FreeCursor(cursor);
cursor = SDL_CreateSystemCursor((SDL_SystemCursor)system_cursor);
SDL_SetCursor(cursor);
}
}
}
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
#ifdef __EMSCRIPTEN__
if (done) {
emscripten_cancel_main_loop();
}
#endif
}
int
main(int argc, char *argv[])
{
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
SDL_assert(SDL_arraysize(cursorNames) == SDL_NUM_SYSTEM_CURSORS);
/* Initialize test framework */
state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
if (!state) {
return 1;
}
if (!SDLTest_CommonDefaultArgs(state, argc, argv) || !SDLTest_CommonInit(state)) {
SDLTest_CommonQuit(state);
return 1;
}
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
SDL_EventState(SDL_DROPTEXT, SDL_ENABLE);
for (i = 0; i < state->num_windows; ++i) {
SDL_Renderer *renderer = state->renderers[i];
SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF);
SDL_RenderClear(renderer);
}
/* Main render loop */
done = 0;
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop(loop, 0, 1);
#else
while (!done) {
loop();
}
#endif
SDL_FreeCursor(cursor);
quit(0);
/* keep the compiler happy ... */
return(0);
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testwm2.c | C | apache-2.0 | 4,677 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "SDL.h"
#include "SDL_test_font.h"
#include "testyuv_cvt.h"
/* 422 (YUY2, etc) formats are the largest */
#define MAX_YUV_SURFACE_SIZE(W, H, P) (H*4*(W+P+1)/2)
/* Return true if the YUV format is packed pixels */
static SDL_bool is_packed_yuv_format(Uint32 format)
{
return (format == SDL_PIXELFORMAT_YUY2 ||
format == SDL_PIXELFORMAT_UYVY ||
format == SDL_PIXELFORMAT_YVYU);
}
/* Create a surface with a good pattern for verifying YUV conversion */
static SDL_Surface *generate_test_pattern(int pattern_size)
{
SDL_Surface *pattern = SDL_CreateRGBSurfaceWithFormat(0, pattern_size, pattern_size, 0, SDL_PIXELFORMAT_RGB24);
if (pattern) {
int i, x, y;
Uint8 *p, c;
const int thickness = 2; /* Important so 2x2 blocks of color are the same, to avoid Cr/Cb interpolation over pixels */
/* R, G, B in alternating horizontal bands */
for (y = 0; y < pattern->h; y += thickness) {
for (i = 0; i < thickness; ++i) {
p = (Uint8 *)pattern->pixels + (y + i) * pattern->pitch + ((y/thickness) % 3);
for (x = 0; x < pattern->w; ++x) {
*p = 0xFF;
p += 3;
}
}
}
/* Black and white in alternating vertical bands */
c = 0xFF;
for (x = 1*thickness; x < pattern->w; x += 2*thickness) {
for (i = 0; i < thickness; ++i) {
p = (Uint8 *)pattern->pixels + (x + i)*3;
for (y = 0; y < pattern->h; ++y) {
SDL_memset(p, c, 3);
p += pattern->pitch;
}
}
if (c) {
c = 0x00;
} else {
c = 0xFF;
}
}
}
return pattern;
}
static SDL_bool verify_yuv_data(Uint32 format, const Uint8 *yuv, int yuv_pitch, SDL_Surface *surface)
{
const int tolerance = 20;
const int size = (surface->h * surface->pitch);
Uint8 *rgb;
SDL_bool result = SDL_FALSE;
rgb = (Uint8 *)SDL_malloc(size);
if (!rgb) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory");
return SDL_FALSE;
}
if (SDL_ConvertPixels(surface->w, surface->h, format, yuv, yuv_pitch, surface->format->format, rgb, surface->pitch) == 0) {
int x, y;
result = SDL_TRUE;
for (y = 0; y < surface->h; ++y) {
const Uint8 *actual = rgb + y * surface->pitch;
const Uint8 *expected = (const Uint8 *)surface->pixels + y * surface->pitch;
for (x = 0; x < surface->w; ++x) {
int deltaR = (int)actual[0] - expected[0];
int deltaG = (int)actual[1] - expected[1];
int deltaB = (int)actual[2] - expected[2];
int distance = (deltaR * deltaR + deltaG * deltaG + deltaB * deltaB);
if (distance > tolerance) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Pixel at %d,%d was 0x%.2x,0x%.2x,0x%.2x, expected 0x%.2x,0x%.2x,0x%.2x, distance = %d\n", x, y, actual[0], actual[1], actual[2], expected[0], expected[1], expected[2], distance);
result = SDL_FALSE;
}
actual += 3;
expected += 3;
}
}
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't convert %s to %s: %s\n", SDL_GetPixelFormatName(format), SDL_GetPixelFormatName(surface->format->format), SDL_GetError());
}
SDL_free(rgb);
return result;
}
static int run_automated_tests(int pattern_size, int extra_pitch)
{
const Uint32 formats[] = {
SDL_PIXELFORMAT_YV12,
SDL_PIXELFORMAT_IYUV,
SDL_PIXELFORMAT_NV12,
SDL_PIXELFORMAT_NV21,
SDL_PIXELFORMAT_YUY2,
SDL_PIXELFORMAT_UYVY,
SDL_PIXELFORMAT_YVYU
};
int i, j;
SDL_Surface *pattern = generate_test_pattern(pattern_size);
const int yuv_len = MAX_YUV_SURFACE_SIZE(pattern->w, pattern->h, extra_pitch);
Uint8 *yuv1 = (Uint8 *)SDL_malloc(yuv_len);
Uint8 *yuv2 = (Uint8 *)SDL_malloc(yuv_len);
int yuv1_pitch, yuv2_pitch;
int result = -1;
if (!pattern || !yuv1 || !yuv2) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't allocate test surfaces");
goto done;
}
/* Verify conversion from YUV formats */
for (i = 0; i < SDL_arraysize(formats); ++i) {
if (!ConvertRGBtoYUV(formats[i], pattern->pixels, pattern->pitch, yuv1, pattern->w, pattern->h, SDL_GetYUVConversionModeForResolution(pattern->w, pattern->h), 0, 100)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "ConvertRGBtoYUV() doesn't support converting to %s\n", SDL_GetPixelFormatName(formats[i]));
goto done;
}
yuv1_pitch = CalculateYUVPitch(formats[i], pattern->w);
if (!verify_yuv_data(formats[i], yuv1, yuv1_pitch, pattern)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed conversion from %s to RGB\n", SDL_GetPixelFormatName(formats[i]));
goto done;
}
}
/* Verify conversion to YUV formats */
for (i = 0; i < SDL_arraysize(formats); ++i) {
yuv1_pitch = CalculateYUVPitch(formats[i], pattern->w) + extra_pitch;
if (SDL_ConvertPixels(pattern->w, pattern->h, pattern->format->format, pattern->pixels, pattern->pitch, formats[i], yuv1, yuv1_pitch) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't convert %s to %s: %s\n", SDL_GetPixelFormatName(pattern->format->format), SDL_GetPixelFormatName(formats[i]), SDL_GetError());
goto done;
}
if (!verify_yuv_data(formats[i], yuv1, yuv1_pitch, pattern)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed conversion from RGB to %s\n", SDL_GetPixelFormatName(formats[i]));
goto done;
}
}
/* Verify conversion between YUV formats */
for (i = 0; i < SDL_arraysize(formats); ++i) {
for (j = 0; j < SDL_arraysize(formats); ++j) {
yuv1_pitch = CalculateYUVPitch(formats[i], pattern->w) + extra_pitch;
yuv2_pitch = CalculateYUVPitch(formats[j], pattern->w) + extra_pitch;
if (SDL_ConvertPixels(pattern->w, pattern->h, pattern->format->format, pattern->pixels, pattern->pitch, formats[i], yuv1, yuv1_pitch) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't convert %s to %s: %s\n", SDL_GetPixelFormatName(pattern->format->format), SDL_GetPixelFormatName(formats[i]), SDL_GetError());
goto done;
}
if (SDL_ConvertPixels(pattern->w, pattern->h, formats[i], yuv1, yuv1_pitch, formats[j], yuv2, yuv2_pitch) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't convert %s to %s: %s\n", SDL_GetPixelFormatName(formats[i]), SDL_GetPixelFormatName(formats[j]), SDL_GetError());
goto done;
}
if (!verify_yuv_data(formats[j], yuv2, yuv2_pitch, pattern)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed conversion from %s to %s\n", SDL_GetPixelFormatName(formats[i]), SDL_GetPixelFormatName(formats[j]));
goto done;
}
}
}
/* Verify conversion between YUV formats in-place */
for (i = 0; i < SDL_arraysize(formats); ++i) {
for (j = 0; j < SDL_arraysize(formats); ++j) {
if (is_packed_yuv_format(formats[i]) != is_packed_yuv_format(formats[j])) {
/* Can't change plane vs packed pixel layout in-place */
continue;
}
yuv1_pitch = CalculateYUVPitch(formats[i], pattern->w) + extra_pitch;
yuv2_pitch = CalculateYUVPitch(formats[j], pattern->w) + extra_pitch;
if (SDL_ConvertPixels(pattern->w, pattern->h, pattern->format->format, pattern->pixels, pattern->pitch, formats[i], yuv1, yuv1_pitch) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't convert %s to %s: %s\n", SDL_GetPixelFormatName(pattern->format->format), SDL_GetPixelFormatName(formats[i]), SDL_GetError());
goto done;
}
if (SDL_ConvertPixels(pattern->w, pattern->h, formats[i], yuv1, yuv1_pitch, formats[j], yuv1, yuv2_pitch) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't convert %s to %s: %s\n", SDL_GetPixelFormatName(formats[i]), SDL_GetPixelFormatName(formats[j]), SDL_GetError());
goto done;
}
if (!verify_yuv_data(formats[j], yuv1, yuv2_pitch, pattern)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed conversion from %s to %s\n", SDL_GetPixelFormatName(formats[i]), SDL_GetPixelFormatName(formats[j]));
goto done;
}
}
}
result = 0;
done:
SDL_free(yuv1);
SDL_free(yuv2);
SDL_FreeSurface(pattern);
return result;
}
int
main(int argc, char **argv)
{
struct {
SDL_bool enable_intrinsics;
int pattern_size;
int extra_pitch;
} automated_test_params[] = {
/* Test: even width and height */
{ SDL_FALSE, 2, 0 },
{ SDL_FALSE, 4, 0 },
/* Test: odd width and height */
{ SDL_FALSE, 1, 0 },
{ SDL_FALSE, 3, 0 },
/* Test: even width and height, extra pitch */
{ SDL_FALSE, 2, 3 },
{ SDL_FALSE, 4, 3 },
/* Test: odd width and height, extra pitch */
{ SDL_FALSE, 1, 3 },
{ SDL_FALSE, 3, 3 },
/* Test: even width and height with intrinsics */
{ SDL_TRUE, 32, 0 },
/* Test: odd width and height with intrinsics */
{ SDL_TRUE, 33, 0 },
{ SDL_TRUE, 37, 0 },
/* Test: even width and height with intrinsics, extra pitch */
{ SDL_TRUE, 32, 3 },
/* Test: odd width and height with intrinsics, extra pitch */
{ SDL_TRUE, 33, 3 },
{ SDL_TRUE, 37, 3 },
};
int arg = 1;
const char *filename;
SDL_Surface *original;
SDL_Surface *converted;
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Texture *output[3];
const char *titles[3] = { "ORIGINAL", "SOFTWARE", "HARDWARE" };
char title[128];
const char *yuv_name;
const char *yuv_mode;
Uint32 rgb_format = SDL_PIXELFORMAT_RGBX8888;
Uint32 yuv_format = SDL_PIXELFORMAT_YV12;
int current = 0;
int pitch;
Uint8 *raw_yuv;
Uint32 then, now, i, iterations = 100;
SDL_bool should_run_automated_tests = SDL_FALSE;
while (argv[arg] && *argv[arg] == '-') {
if (SDL_strcmp(argv[arg], "--jpeg") == 0) {
SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_JPEG);
} else if (SDL_strcmp(argv[arg], "--bt601") == 0) {
SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_BT601);
} else if (SDL_strcmp(argv[arg], "--bt709") == 0) {
SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_BT709);
} else if (SDL_strcmp(argv[arg], "--auto") == 0) {
SDL_SetYUVConversionMode(SDL_YUV_CONVERSION_AUTOMATIC);
} else if (SDL_strcmp(argv[arg], "--yv12") == 0) {
yuv_format = SDL_PIXELFORMAT_YV12;
} else if (SDL_strcmp(argv[arg], "--iyuv") == 0) {
yuv_format = SDL_PIXELFORMAT_IYUV;
} else if (SDL_strcmp(argv[arg], "--yuy2") == 0) {
yuv_format = SDL_PIXELFORMAT_YUY2;
} else if (SDL_strcmp(argv[arg], "--uyvy") == 0) {
yuv_format = SDL_PIXELFORMAT_UYVY;
} else if (SDL_strcmp(argv[arg], "--yvyu") == 0) {
yuv_format = SDL_PIXELFORMAT_YVYU;
} else if (SDL_strcmp(argv[arg], "--nv12") == 0) {
yuv_format = SDL_PIXELFORMAT_NV12;
} else if (SDL_strcmp(argv[arg], "--nv21") == 0) {
yuv_format = SDL_PIXELFORMAT_NV21;
} else if (SDL_strcmp(argv[arg], "--rgb555") == 0) {
rgb_format = SDL_PIXELFORMAT_RGB555;
} else if (SDL_strcmp(argv[arg], "--rgb565") == 0) {
rgb_format = SDL_PIXELFORMAT_RGB565;
} else if (SDL_strcmp(argv[arg], "--rgb24") == 0) {
rgb_format = SDL_PIXELFORMAT_RGB24;
} else if (SDL_strcmp(argv[arg], "--argb") == 0) {
rgb_format = SDL_PIXELFORMAT_ARGB8888;
} else if (SDL_strcmp(argv[arg], "--abgr") == 0) {
rgb_format = SDL_PIXELFORMAT_ABGR8888;
} else if (SDL_strcmp(argv[arg], "--rgba") == 0) {
rgb_format = SDL_PIXELFORMAT_RGBA8888;
} else if (SDL_strcmp(argv[arg], "--bgra") == 0) {
rgb_format = SDL_PIXELFORMAT_BGRA8888;
} else if (SDL_strcmp(argv[arg], "--automated") == 0) {
should_run_automated_tests = SDL_TRUE;
} else {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Usage: %s [--jpeg|--bt601|-bt709|--auto] [--yv12|--iyuv|--yuy2|--uyvy|--yvyu|--nv12|--nv21] [--rgb555|--rgb565|--rgb24|--argb|--abgr|--rgba|--bgra] [image_filename]\n", argv[0]);
return 1;
}
++arg;
}
/* Run automated tests */
if (should_run_automated_tests) {
for (i = 0; i < SDL_arraysize(automated_test_params); ++i) {
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "Running automated test, pattern size %d, extra pitch %d, intrinsics %s\n",
automated_test_params[i].pattern_size,
automated_test_params[i].extra_pitch,
automated_test_params[i].enable_intrinsics ? "enabled" : "disabled");
if (run_automated_tests(automated_test_params[i].pattern_size, automated_test_params[i].extra_pitch) < 0) {
return 2;
}
}
return 0;
}
if (argv[arg]) {
filename = argv[arg];
} else {
filename = "testyuv.bmp";
}
original = SDL_ConvertSurfaceFormat(SDL_LoadBMP(filename), SDL_PIXELFORMAT_RGB24, 0);
if (!original) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError());
return 3;
}
raw_yuv = SDL_calloc(1, MAX_YUV_SURFACE_SIZE(original->w, original->h, 0));
ConvertRGBtoYUV(yuv_format, original->pixels, original->pitch, raw_yuv, original->w, original->h,
SDL_GetYUVConversionModeForResolution(original->w, original->h),
0, 100);
pitch = CalculateYUVPitch(yuv_format, original->w);
converted = SDL_CreateRGBSurfaceWithFormat(0, original->w, original->h, 0, rgb_format);
if (!converted) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create converted surface: %s\n", SDL_GetError());
return 3;
}
then = SDL_GetTicks();
for ( i = 0; i < iterations; ++i ) {
SDL_ConvertPixels(original->w, original->h, yuv_format, raw_yuv, pitch, rgb_format, converted->pixels, converted->pitch);
}
now = SDL_GetTicks();
SDL_LogInfo(SDL_LOG_CATEGORY_APPLICATION, "%d iterations in %d ms, %.2fms each\n", iterations, (now - then), (float)(now - then)/iterations);
window = SDL_CreateWindow("YUV test",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
original->w, original->h,
0);
if (!window) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError());
return 4;
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (!renderer) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError());
return 4;
}
output[0] = SDL_CreateTextureFromSurface(renderer, original);
output[1] = SDL_CreateTextureFromSurface(renderer, converted);
output[2] = SDL_CreateTexture(renderer, yuv_format, SDL_TEXTUREACCESS_STREAMING, original->w, original->h);
if (!output[0] || !output[1] || !output[2]) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
return 5;
}
SDL_UpdateTexture(output[2], NULL, raw_yuv, pitch);
yuv_name = SDL_GetPixelFormatName(yuv_format);
if (SDL_strncmp(yuv_name, "SDL_PIXELFORMAT_", 16) == 0) {
yuv_name += 16;
}
switch (SDL_GetYUVConversionModeForResolution(original->w, original->h)) {
case SDL_YUV_CONVERSION_JPEG:
yuv_mode = "JPEG";
break;
case SDL_YUV_CONVERSION_BT601:
yuv_mode = "BT.601";
break;
case SDL_YUV_CONVERSION_BT709:
yuv_mode = "BT.709";
break;
default:
yuv_mode = "UNKNOWN";
break;
}
{ int done = 0;
while ( !done )
{
SDL_Event event;
while (SDL_PollEvent(&event) > 0) {
if (event.type == SDL_QUIT) {
done = 1;
}
if (event.type == SDL_KEYDOWN) {
if (event.key.keysym.sym == SDLK_ESCAPE) {
done = 1;
} else if (event.key.keysym.sym == SDLK_LEFT) {
--current;
} else if (event.key.keysym.sym == SDLK_RIGHT) {
++current;
}
}
if (event.type == SDL_MOUSEBUTTONDOWN) {
if (event.button.x < (original->w/2)) {
--current;
} else {
++current;
}
}
}
/* Handle wrapping */
if (current < 0) {
current += SDL_arraysize(output);
}
if (current >= SDL_arraysize(output)) {
current -= SDL_arraysize(output);
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, output[current], NULL, NULL);
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
if (current == 0) {
SDLTest_DrawString(renderer, 4, 4, titles[current]);
} else {
SDL_snprintf(title, sizeof(title), "%s %s %s", titles[current], yuv_name, yuv_mode);
SDLTest_DrawString(renderer, 4, 4, title);
}
SDL_RenderPresent(renderer);
SDL_Delay(10);
}
}
SDL_Quit();
return 0;
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testyuv.c | C | apache-2.0 | 18,775 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
#include "SDL.h"
#include "testyuv_cvt.h"
static float clip3(float x, float y, float z)
{
return ((z < x) ? x : ((z > y) ? y : z));
}
static void RGBtoYUV(Uint8 * rgb, int *yuv, SDL_YUV_CONVERSION_MODE mode, int monochrome, int luminance)
{
if (mode == SDL_YUV_CONVERSION_JPEG) {
/* Full range YUV */
yuv[0] = (int)(0.299 * rgb[0] + 0.587 * rgb[1] + 0.114 * rgb[2]);
yuv[1] = (int)((rgb[2] - yuv[0]) * 0.565 + 128);
yuv[2] = (int)((rgb[0] - yuv[0]) * 0.713 + 128);
} else {
// This formula is from Microsoft's documentation:
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd206750(v=vs.85).aspx
// L = Kr * R + Kb * B + (1 - Kr - Kb) * G
// Y = floor(2^(M-8) * (219*(L-Z)/S + 16) + 0.5);
// U = clip3(0, (2^M)-1, floor(2^(M-8) * (112*(B-L) / ((1-Kb)*S) + 128) + 0.5));
// V = clip3(0, (2^M)-1, floor(2^(M-8) * (112*(R-L) / ((1-Kr)*S) + 128) + 0.5));
float S, Z, R, G, B, L, Kr, Kb, Y, U, V;
if (mode == SDL_YUV_CONVERSION_BT709) {
/* BT.709 */
Kr = 0.2126f;
Kb = 0.0722f;
} else {
/* BT.601 */
Kr = 0.299f;
Kb = 0.114f;
}
S = 255.0f;
Z = 0.0f;
R = rgb[0];
G = rgb[1];
B = rgb[2];
L = Kr * R + Kb * B + (1 - Kr - Kb) * G;
Y = (Uint8)SDL_floorf((219*(L-Z)/S + 16) + 0.5f);
U = (Uint8)clip3(0, 255, SDL_floorf((112.0f*(B-L) / ((1.0f-Kb)*S) + 128) + 0.5f));
V = (Uint8)clip3(0, 255, SDL_floorf((112.0f*(R-L) / ((1.0f-Kr)*S) + 128) + 0.5f));
yuv[0] = (Uint8)Y;
yuv[1] = (Uint8)U;
yuv[2] = (Uint8)V;
}
if (monochrome) {
yuv[1] = 128;
yuv[2] = 128;
}
if (luminance != 100) {
yuv[0] = yuv[0] * luminance / 100;
if (yuv[0] > 255)
yuv[0] = 255;
}
}
static void ConvertRGBtoPlanar2x2(Uint32 format, Uint8 *src, int pitch, Uint8 *out, int w, int h, SDL_YUV_CONVERSION_MODE mode, int monochrome, int luminance)
{
int x, y;
int yuv[4][3];
Uint8 *Y1, *Y2, *U, *V;
Uint8 *rgb1, *rgb2;
int rgb_row_advance = (pitch - w*3) + pitch;
int UV_advance;
rgb1 = src;
rgb2 = src + pitch;
Y1 = out;
Y2 = Y1 + w;
switch (format) {
case SDL_PIXELFORMAT_YV12:
V = (Y1 + h * w);
U = V + ((h + 1)/2)*((w + 1)/2);
UV_advance = 1;
break;
case SDL_PIXELFORMAT_IYUV:
U = (Y1 + h * w);
V = U + ((h + 1)/2)*((w + 1)/2);
UV_advance = 1;
break;
case SDL_PIXELFORMAT_NV12:
U = (Y1 + h * w);
V = U + 1;
UV_advance = 2;
break;
case SDL_PIXELFORMAT_NV21:
V = (Y1 + h * w);
U = V + 1;
UV_advance = 2;
break;
default:
SDL_assert(!"Unsupported planar YUV format");
return;
}
for (y = 0; y < (h - 1); y += 2) {
for (x = 0; x < (w - 1); x += 2) {
RGBtoYUV(rgb1, yuv[0], mode, monochrome, luminance);
rgb1 += 3;
*Y1++ = (Uint8)yuv[0][0];
RGBtoYUV(rgb1, yuv[1], mode, monochrome, luminance);
rgb1 += 3;
*Y1++ = (Uint8)yuv[1][0];
RGBtoYUV(rgb2, yuv[2], mode, monochrome, luminance);
rgb2 += 3;
*Y2++ = (Uint8)yuv[2][0];
RGBtoYUV(rgb2, yuv[3], mode, monochrome, luminance);
rgb2 += 3;
*Y2++ = (Uint8)yuv[3][0];
*U = (Uint8)SDL_floorf((yuv[0][1] + yuv[1][1] + yuv[2][1] + yuv[3][1])/4.0f + 0.5f);
U += UV_advance;
*V = (Uint8)SDL_floorf((yuv[0][2] + yuv[1][2] + yuv[2][2] + yuv[3][2])/4.0f + 0.5f);
V += UV_advance;
}
/* Last column */
if (x == (w - 1)) {
RGBtoYUV(rgb1, yuv[0], mode, monochrome, luminance);
rgb1 += 3;
*Y1++ = (Uint8)yuv[0][0];
RGBtoYUV(rgb2, yuv[2], mode, monochrome, luminance);
rgb2 += 3;
*Y2++ = (Uint8)yuv[2][0];
*U = (Uint8)SDL_floorf((yuv[0][1] + yuv[2][1])/2.0f + 0.5f);
U += UV_advance;
*V = (Uint8)SDL_floorf((yuv[0][2] + yuv[2][2])/2.0f + 0.5f);
V += UV_advance;
}
Y1 += w;
Y2 += w;
rgb1 += rgb_row_advance;
rgb2 += rgb_row_advance;
}
/* Last row */
if (y == (h - 1)) {
for (x = 0; x < (w - 1); x += 2) {
RGBtoYUV(rgb1, yuv[0], mode, monochrome, luminance);
rgb1 += 3;
*Y1++ = (Uint8)yuv[0][0];
RGBtoYUV(rgb1, yuv[1], mode, monochrome, luminance);
rgb1 += 3;
*Y1++ = (Uint8)yuv[1][0];
*U = (Uint8)SDL_floorf((yuv[0][1] + yuv[1][1])/2.0f + 0.5f);
U += UV_advance;
*V = (Uint8)SDL_floorf((yuv[0][2] + yuv[1][2])/2.0f + 0.5f);
V += UV_advance;
}
/* Last column */
if (x == (w - 1)) {
RGBtoYUV(rgb1, yuv[0], mode, monochrome, luminance);
*Y1++ = (Uint8)yuv[0][0];
*U = (Uint8)yuv[0][1];
U += UV_advance;
*V = (Uint8)yuv[0][2];
V += UV_advance;
}
}
}
static void ConvertRGBtoPacked4(Uint32 format, Uint8 *src, int pitch, Uint8 *out, int w, int h, SDL_YUV_CONVERSION_MODE mode, int monochrome, int luminance)
{
int x, y;
int yuv[2][3];
Uint8 *Y1, *Y2, *U, *V;
Uint8 *rgb;
int rgb_row_advance = (pitch - w*3);
rgb = src;
switch (format) {
case SDL_PIXELFORMAT_YUY2:
Y1 = out;
U = out+1;
Y2 = out+2;
V = out+3;
break;
case SDL_PIXELFORMAT_UYVY:
U = out;
Y1 = out+1;
V = out+2;
Y2 = out+3;
break;
case SDL_PIXELFORMAT_YVYU:
Y1 = out;
V = out+1;
Y2 = out+2;
U = out+3;
break;
default:
SDL_assert(!"Unsupported packed YUV format");
return;
}
for (y = 0; y < h; ++y) {
for (x = 0; x < (w - 1); x += 2) {
RGBtoYUV(rgb, yuv[0], mode, monochrome, luminance);
rgb += 3;
*Y1 = (Uint8)yuv[0][0];
Y1 += 4;
RGBtoYUV(rgb, yuv[1], mode, monochrome, luminance);
rgb += 3;
*Y2 = (Uint8)yuv[1][0];
Y2 += 4;
*U = (Uint8)SDL_floorf((yuv[0][1] + yuv[1][1])/2.0f + 0.5f);
U += 4;
*V = (Uint8)SDL_floorf((yuv[0][2] + yuv[1][2])/2.0f + 0.5f);
V += 4;
}
/* Last column */
if (x == (w - 1)) {
RGBtoYUV(rgb, yuv[0], mode, monochrome, luminance);
rgb += 3;
*Y2 = *Y1 = (Uint8)yuv[0][0];
Y1 += 4;
Y2 += 4;
*U = (Uint8)yuv[0][1];
U += 4;
*V = (Uint8)yuv[0][2];
V += 4;
}
rgb += rgb_row_advance;
}
}
SDL_bool ConvertRGBtoYUV(Uint32 format, Uint8 *src, int pitch, Uint8 *out, int w, int h, SDL_YUV_CONVERSION_MODE mode, int monochrome, int luminance)
{
switch (format)
{
case SDL_PIXELFORMAT_YV12:
case SDL_PIXELFORMAT_IYUV:
case SDL_PIXELFORMAT_NV12:
case SDL_PIXELFORMAT_NV21:
ConvertRGBtoPlanar2x2(format, src, pitch, out, w, h, mode, monochrome, luminance);
return SDL_TRUE;
case SDL_PIXELFORMAT_YUY2:
case SDL_PIXELFORMAT_UYVY:
case SDL_PIXELFORMAT_YVYU:
ConvertRGBtoPacked4(format, src, pitch, out, w, h, mode, monochrome, luminance);
return SDL_TRUE;
default:
return SDL_FALSE;
}
}
int CalculateYUVPitch(Uint32 format, int width)
{
switch (format)
{
case SDL_PIXELFORMAT_YV12:
case SDL_PIXELFORMAT_IYUV:
case SDL_PIXELFORMAT_NV12:
case SDL_PIXELFORMAT_NV21:
return width;
case SDL_PIXELFORMAT_YUY2:
case SDL_PIXELFORMAT_UYVY:
case SDL_PIXELFORMAT_YVYU:
return 4*((width + 1)/2);
default:
return 0;
}
}
/* vi: set ts=4 sw=4 expandtab: */
| YifuLiu/AliOS-Things | components/SDL2/test/testyuv_cvt.c | C | apache-2.0 | 8,503 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* These functions are designed for testing correctness, not for speed */
extern SDL_bool ConvertRGBtoYUV(Uint32 format, Uint8 *src, int pitch, Uint8 *out, int w, int h, SDL_YUV_CONVERSION_MODE mode, int monochrome, int luminance);
extern int CalculateYUVPitch(Uint32 format, int width);
| YifuLiu/AliOS-Things | components/SDL2/test/testyuv_cvt.h | C | apache-2.0 | 695 |
/*
Copyright (C) 1997-2020 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely.
*/
/* Simple test of the SDL threading code */
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include "SDL.h"
#define NUMTHREADS 10
static SDL_atomic_t time_for_threads_to_die[NUMTHREADS];
/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
static void
quit(int rc)
{
SDL_Quit();
exit(rc);
}
int SDLCALL
SubThreadFunc(void *data)
{
while (!*(int volatile *) data) {
; /* SDL_Delay(10); *//* do nothing */
}
return 0;
}
int SDLCALL
ThreadFunc(void *data)
{
SDL_Thread *sub_threads[NUMTHREADS];
int flags[NUMTHREADS];
int i;
int tid = (int) (uintptr_t) data;
SDL_Log("Creating Thread %d\n", tid);
for (i = 0; i < NUMTHREADS; i++) {
char name[64];
SDL_snprintf(name, sizeof (name), "Child%d_%d", tid, i);
flags[i] = 0;
sub_threads[i] = SDL_CreateThread(SubThreadFunc, name, &flags[i]);
}
SDL_Log("Thread '%d' waiting for signal\n", tid);
while (SDL_AtomicGet(&time_for_threads_to_die[tid]) != 1) {
; /* do nothing */
}
SDL_Log("Thread '%d' sending signals to subthreads\n", tid);
for (i = 0; i < NUMTHREADS; i++) {
flags[i] = 1;
SDL_WaitThread(sub_threads[i], NULL);
}
SDL_Log("Thread '%d' exiting!\n", tid);
return 0;
}
int
main(int argc, char *argv[])
{
SDL_Thread *threads[NUMTHREADS];
int i;
/* Enable standard application logging */
SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
/* Load the SDL library */
if (SDL_Init(0) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
return (1);
}
signal(SIGSEGV, SIG_DFL);
for (i = 0; i < NUMTHREADS; i++) {
char name[64];
SDL_snprintf(name, sizeof (name), "Parent%d", i);
SDL_AtomicSet(&time_for_threads_to_die[i], 0);
threads[i] = SDL_CreateThread(ThreadFunc, name, (void*) (uintptr_t) i);
if (threads[i] == NULL) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create thread: %s\n", SDL_GetError());
quit(1);
}
}
for (i = 0; i < NUMTHREADS; i++) {
SDL_AtomicSet(&time_for_threads_to_die[i], 1);
}
for (i = 0; i < NUMTHREADS; i++) {
SDL_WaitThread(threads[i], NULL);
}
SDL_Quit();
return (0);
}
| YifuLiu/AliOS-Things | components/SDL2/test/torturethread.c | C | apache-2.0 | 2,859 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
extern int audio_install_codec_driver();
extern void sound_example_wav_entry(int argc, char **argv);
extern void sound_example_loopback_entry(int argc, char **argv);
void sound_example_setvol_entry(int argc, char **argv);
void sound_example_getvol_entry(int argc, char **argv);
static void sound_example_install_driver(int argc, char **argv)
{
printf("sound install driver test begin ...\r\n");
audio_install_codec_driver();
printf("sound install driver test end !!!\r\n");
return;
}
static void sound_example_wav(int argc, char **argv)
{
printf("sound wav player test begin ...\r\n");
sound_example_wav_entry(argc, argv);
printf("sound wav player test end !!!\r\n");
return;
}
static void sound_example_loopback(int argc, char **argv)
{
sound_example_loopback_entry(argc, argv);
return;
}
static void sound_example_setvol(int argc, char **argv)
{
printf("sound setvol test begin ...\r\n");
sound_example_setvol_entry(argc, argv);
printf("sound setvol test end !!!\r\n");
return;
}
static void sound_example_getvol(int argc, char **argv)
{
printf("sound getvol test begin ...\r\n");
sound_example_getvol_entry(argc, argv);
printf("sound getvol test end !!!\r\n");
return;
}
#if AOS_COMP_CLI
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(sound_example_install_driver, sound_install_driver, sound install driver test example)
ALIOS_CLI_CMD_REGISTER(sound_example_wav, sound_wav, sound wav player test example)
ALIOS_CLI_CMD_REGISTER(sound_example_loopback, sound_loopback, sound loopback test example)
ALIOS_CLI_CMD_REGISTER(sound_example_setvol, sound_setvol, sound set volume test example)
ALIOS_CLI_CMD_REGISTER(sound_example_getvol, sound_getvol, sound get volume test example)
#endif
| YifuLiu/AliOS-Things | components/a2sa/example/sound_example.c | C | apache-2.0 | 1,890 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifdef HAAS_AUDIO_DEMO
#include <posix/pthread.h>
#else
#include <pthread.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "sound_pcm.h"
#include "audio_drv.h"
#include "ulog/ulog.h"
#define LOG_TAG "[sound_example_lb]"
#define AUDIO_PLAYER_HIGH_STACKSIZE 8192
#define AUDIO_PLAYER_DEFAULT_PRIORITY 33
static char *param = NULL;
static pthread_cond_t g_play_cond;
static pthread_mutex_t g_play_mutex;
static pthread_t g_play_thread;
static bool bCreateAudioThreadFlag = false;
static void sound_loopback_thread(void *arg)
{
aos_pcm_t *pb_pcm = NULL, *cap_pcm = NULL;
unsigned char * dataBuf = NULL;
unsigned int buf_size = 0;
//int freq = 22050, channels = 1;
int freq = 16000, channels = 1;
int ret = -1;
LOGD(LOG_TAG, "%s:%d: sound_loopback_thread entry!!", __func__, __LINE__);
buf_size = freq * channels * 2 / 5;
dataBuf = (unsigned char *)malloc(buf_size);
if(!dataBuf) {
LOGE(LOG_TAG, "%s:%d: malloc %d failed. ", __func__, __LINE__, buf_size);
return 0;
}
while(1) {
if(!strcmp(param, "start")) {
if(!pb_pcm) {
LOGD(LOG_TAG, "%s:%d: open capture & playback stream!!", __func__, __LINE__);
/* open playback stream */
ret = aos_pcm_open(&pb_pcm, "default", AOS_PCM_STREAM_PLAYBACK, 0);
if(!ret) {
aos_pcm_hw_params_alloca(&pb_pcm->hw_params);
aos_pcm_sw_params_alloca(&pb_pcm->sw_params);
aos_pcm_sw_params_any(pb_pcm->sw_params);
aos_pcm_set_params(pb_pcm, AOSRV_PCM_FORMAT_S16_LE, AOS_PCM_ACCESS_RW_INTERLEAVED, channels, freq, 0, 0);
aos_pcm_prepare(pb_pcm);
aos_pcm_start(pb_pcm);
} else {
LOGE(LOG_TAG, "%s:%d: open playback stream failed. ", __func__, __LINE__);
}
}
if(!cap_pcm) {
/* open capture stream */
ret = aos_pcm_open(&cap_pcm, "default", AOS_PCM_STREAM_CAPTURE, 0);
if(!ret) {
aos_pcm_hw_params_alloca(&cap_pcm->hw_params);
aos_pcm_sw_params_alloca(&cap_pcm->sw_params);
aos_pcm_sw_params_any(cap_pcm->sw_params);
aos_pcm_set_params(cap_pcm, AOSRV_PCM_FORMAT_S16_LE, AOS_PCM_ACCESS_RW_INTERLEAVED, channels, freq, 0, 0);
aos_pcm_prepare(cap_pcm);
aos_pcm_start(cap_pcm);
} else {
LOGE(LOG_TAG, "%s:%d: open capture stream failed. ", __func__, __LINE__);
}
}
ret = aos_pcm_readi(cap_pcm, dataBuf, aos_pcm_bytes_to_frames(cap_pcm, buf_size));
if(ret > 0) {
//LOGD(LOG_TAG, "%s:%d: readi frames(%d) bytes(%d) successfully. ", __func__, __LINE__, ret, aos_pcm_frames_to_bytes(cap_pcm, ret));
aos_pcm_writei(pb_pcm, dataBuf, aos_pcm_bytes_to_frames(pb_pcm, aos_pcm_frames_to_bytes(cap_pcm, ret)));
}
} else {
if(pb_pcm) {
LOGD(LOG_TAG, "%s:%d: close capture & playback stream!!", __func__, __LINE__);
//aos_pcm_drain(pb_pcm);
aos_pcm_stop(pb_pcm);
aos_pcm_close(pb_pcm);
pb_pcm = NULL;
}
if(cap_pcm) {
aos_pcm_stop(cap_pcm);
aos_pcm_close(cap_pcm);
cap_pcm = NULL;
}
usleep(200*1000);
}
}
return 0;
}
static void sound_example_loopback_init(void)
{
if(bCreateAudioThreadFlag) {
return;
}
LOGD(LOG_TAG, "%s:%d, -->>", __func__, __LINE__);
pthread_attr_t attr;
struct sched_param sched;
pthread_cond_init(&g_play_cond, NULL);
pthread_mutex_init(&g_play_mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, AUDIO_PLAYER_HIGH_STACKSIZE);
sched.sched_priority = AUDIO_PLAYER_DEFAULT_PRIORITY;
sched.slice = 0;
pthread_attr_setschedparam(&attr, &sched);
pthread_create(&g_play_thread, &attr, sound_loopback_thread, NULL);
if (g_play_thread) {
pthread_setname_np(g_play_thread, "soundplaythread");
}
pthread_attr_destroy(&attr);
bCreateAudioThreadFlag = true;
}
void sound_example_loopback_entry(int argc, char **argv)
{
if (argc < 2) {
LOGD(LOG_TAG, "%s:%d: Usage: %s start/stop ", __func__, __LINE__, argv[0]);
return;
}
param = strdup(argv[1]);
if(param && !strcmp(param, "start"))
{
printf("sound loopback test begin ...\r\n");
} else {
printf("sound loopback test end !!!\r\n");
}
sound_example_loopback_init();
} | YifuLiu/AliOS-Things | components/a2sa/example/sound_example_lb.c | C | apache-2.0 | 4,889 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "sound_pcm.h"
#include "sound_mixer.h"
#include "ulog/ulog.h"
#define LOG_TAG "[sound_example_vol]"
void sound_example_setvol_entry(int argc, char **argv)
{
int volume = 0;
if (argc < 2) {
LOGE(LOG_TAG, "%s:%d: Usage: %s vaue, e.g. >> setvol 90 ", __func__, __LINE__, argv[0]);
return;
}
volume = atoi(argv[1]);
aos_set_master_volume(volume);
}
void sound_example_getvol_entry(int argc, char **argv)
{
int volume = 0;
aos_get_master_volume(&volume);
LOGD(LOG_TAG, "%s:%d: get volume %d", __func__, __LINE__, volume);
} | YifuLiu/AliOS-Things | components/a2sa/example/sound_example_vol.c | C | apache-2.0 | 722 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifdef HAAS_AUDIO_DEMO
#include <posix/pthread.h>
#else
#include <pthread.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include "sound_pcm.h"
#include "sound_mixer.h"
#include "audio_drv.h"
#include "ulog/ulog.h"
#define LOG_TAG "[sound_example_wav]"
#define ID_RIFF 0x46464952
#define ID_WAVE 0x45564157
#define ID_FMT 0x20746d66
#define ID_DATA 0x61746164
#define AUDIO_PLAYER_HIGH_STACKSIZE 8192
#define AUDIO_PLAYER_DEFAULT_PRIORITY 33
struct riff_wave_header {
uint32_t riff_id;
uint32_t riff_sz;
uint32_t wave_id;
};
struct chunk_header {
uint32_t id;
uint32_t sz;
};
struct chunk_fmt {
uint16_t audio_format;
uint16_t num_channels;
uint32_t sample_rate;
uint32_t byte_rate;
uint16_t block_align;
uint16_t bits_per_sample;
};
static pthread_cond_t g_play_cond;
static pthread_mutex_t g_play_mutex;
static pthread_t g_play_thread;
static bool bCreateAudioThreadFlag = false;
static struct chunk_fmt chunk_fmt;
static unsigned int period_size = 3200;
static unsigned int period_count = 1;
static unsigned int total_cnt = 0;
static char *filename;
static int play_sample(FILE *file, unsigned int channels, unsigned int rate, unsigned int bits, unsigned int period_size,
unsigned int period_count)
{
char *buffer;
int size;
int num_read, frame_size;
int ret = -1;
aos_pcm_t *pcm;
aos_pcm_format_t format;
LOGD(LOG_TAG, "%s:%d: channels %d, sample_rate %d, sample_bits %d, period_size %d, period_count %d", __func__, __LINE__,
channels, rate, bits, period_size, period_count);
ret = aos_pcm_open(&pcm, "default", AOS_PCM_STREAM_PLAYBACK, 0);
if (ret < 0) {
LOGE(LOG_TAG, "%s:%d, could NOT open audio device", __func__, __LINE__);
return -1;
}
switch(bits) {
case 16:
format = AOSRV_PCM_FORMAT_S16_LE;
break;
case 24:
format = AOSRV_PCM_FORMAT_S24_LE;
break;
case 32:
format = AOSRV_PCM_FORMAT_S32_LE;
break;
default:
format = AOSRV_PCM_FORMAT_S16_LE;
break;
}
aos_pcm_set_params(pcm, format, AOS_PCM_ACCESS_RW_INTERLEAVED, channels, rate, 0, 0);
aos_pcm_prepare(pcm);
frame_size = channels * bits / 8;
//size = period_size * period_count * frame_size;
size = rate /10 * frame_size;
LOGD(LOG_TAG, "%s:%d, size = %d", __func__, __LINE__, size);
buffer = malloc(size);
if (!buffer) {
LOGE(LOG_TAG, "%s:%d: failed to malloc %d bytes", __func__, __LINE__, size);
free(buffer);
aos_pcm_close(pcm);
return -1;
}
aos_pcm_start(pcm);
do {
num_read = fread(buffer, 1, size, file);
if (num_read > 0) {
if (aos_pcm_writei(pcm, buffer, num_read/frame_size) < 0) {
LOGE(LOG_TAG, "%s:%d: aos_pcm_writei error. ", __func__, __LINE__);
break;
}
}
} while (num_read > 0);
//aos_pcm_drain(pcm);
aos_pcm_stop(pcm);
aos_pcm_close(pcm);
free(buffer);
return 0;
}
static void sound_wav_thread(void *arg)
{
FILE *file;
struct riff_wave_header riff_wave_header;
struct chunk_header chunk_header;
int more_chunks = 1;
while(1) {
if(total_cnt <= 0) {
LOGD(LOG_TAG, "%s:%d, wav player end !!!", __func__, __LINE__);
pthread_cond_wait(&g_play_cond, &g_play_mutex);
}
total_cnt --;
if(!filename) {
total_cnt = 0;
continue;
}
file = fopen(filename, "rb");
if (!file) {
LOGE(LOG_TAG, "%s:%d, failed to open file '%s'", __func__, __LINE__, filename);
total_cnt = 0;
continue;
}
LOGD(LOG_TAG, "%s:%d, open '%s' successfully", __func__, __LINE__, filename);
fread(&riff_wave_header, sizeof(riff_wave_header), 1, file);
if ((riff_wave_header.riff_id != ID_RIFF) ||
(riff_wave_header.wave_id != ID_WAVE)) {
LOGE(LOG_TAG, "%s:%d, Error: '%s' is not a riff/wave file", __func__, __LINE__, filename);
total_cnt = 0;
fclose(file);
continue;
}
do {
fread(&chunk_header, sizeof(chunk_header), 1, file);
switch (chunk_header.id) {
case ID_FMT:
fread(&chunk_fmt, sizeof(chunk_fmt), 1, file);
/* If the format header is larger, skip the rest */
if (chunk_header.sz > sizeof(chunk_fmt))
fseek(file, chunk_header.sz - sizeof(chunk_fmt), SEEK_CUR);
break;
case ID_DATA:
/* Stop looking for chunks */
more_chunks = 0;
break;
default:
/* Unknown chunk, skip bytes */
fseek(file, chunk_header.sz, SEEK_CUR);
}
} while (more_chunks);
if(play_sample(file, chunk_fmt.num_channels, chunk_fmt.sample_rate, chunk_fmt.bits_per_sample, period_size, period_count) < 0) {
total_cnt = 0;
}
fclose(file);
}
return 0;
}
static void sound_wav_init(void)
{
if(bCreateAudioThreadFlag) {
return;
}
LOGD(LOG_TAG, "%s:%d, -->>", __func__, __LINE__);
pthread_attr_t attr;
struct sched_param sched;
pthread_cond_init(&g_play_cond, NULL);
pthread_mutex_init(&g_play_mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, AUDIO_PLAYER_HIGH_STACKSIZE);
sched.sched_priority = AUDIO_PLAYER_DEFAULT_PRIORITY;
sched.slice = 0;
pthread_attr_setschedparam(&attr, &sched);
pthread_create(&g_play_thread, &attr, sound_wav_thread, NULL);
if (g_play_thread) {
pthread_setname_np(g_play_thread, "wav_player_thread");
}
pthread_attr_destroy(&attr);
bCreateAudioThreadFlag = true;
}
void sound_example_wav_entry(int argc, char **argv)
{
if (argc < 3) {
LOGD(LOG_TAG, "%s:%d: Usage: %s file.wav cnt ", __func__, __LINE__, argv[0]);
return;
}
filename = strdup(argv[1]);
total_cnt = atoi(argv[2]);
sound_wav_init();
pthread_cond_signal(&g_play_cond);
}
| YifuLiu/AliOS-Things | components/a2sa/example/sound_example_wav.c | C | apache-2.0 | 6,378 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef SOUND_CONTROL_H
#define SOUND_CONTROL_H
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <aos/list.h>
#include <aos/kernel.h>
#ifndef HAAS_AUDIO_DEMO
#include <sys/ioctl.h>
#endif
#include "audio_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup a2sa_api a2sa
* @ingroup aos_components
* @{
*/
/**
* @}
*/
/** @defgroup a2sa_mixer_api mixer
* @ingroup a2sa_api
* @{
*/
/* 音频mixer设备节点描述信息 */
typedef struct {
int fd; /**< 声卡mixer设备节点fd值,通过open()函数获取 */
int card; /**< 声卡ID */
char *name; /**< 声卡mixer设备节点名字,例如"/dev/controlC0" */
struct audio_ctl_card_info card_info; /**< 声卡基础信息,例如声卡驱动名字 */
struct audio_ctl_elem_info *elem_info; /**< 声卡配置信息元素地址 */
unsigned int count; /**< 声卡配置信息元素个数 */
} aos_mixer_t;
/**
* 打开ID为card的声卡的mixer设备节点
*
* @param[out] mixer 保存mixer设备节点信息的二级指针
* @param[in] card 期望打开的声卡ID
*
* @return 0 on success, negative error on failure.
*/
int aos_mixer_open(aos_mixer_t **mixer, int card);
/**
* 打印当前声卡mixer设备节点的所有属性信息
*
* @param[in] mixer 保存mixer设备节点信息的指针
*
* @return 0 on success, negative error on failure.
*/
int aos_mixer_print_info(aos_mixer_t *mixer);
/**
* 设置mixer设备节点中名为name的属性值为int value
*
* @param[in] mixer 保存mixer设备节点信息的指针
* @param[in] name 期望设置的目标属性名字
* @param[in] value 期望设置到名字为name的目标属性的int值
*
* @return 0 on success, negative error on failure.
*/
int aos_mixer_set_int_value(aos_mixer_t *mixer, char *name, int value);
/**
* 获取mixer设备节点中名为name的属性值,并保存在value指针中
*
* @param[in] mixer 保存mixer设备节点信息的指针
* @param[in] name 期望获取的目标属性名字
* @param[out] *value 获取到的目标属性值保存在int *value中
*
* @return 0 on success, negative error on failure.
*/
int aos_mixer_get_int_value(aos_mixer_t *mixer, char *name, int *value);
/**
* 关闭mixer设备节点
*
* @param[in] mixer 期望关闭的mixer设备节点信息的指针
*
* @return 0 on success, negative error on failure.
*/
int aos_mixer_close(aos_mixer_t *mixer);
/**
* 设置所有声卡中名为“Master Volume TX”的属性的值为volume
*
* @param[in] volume 期望往声卡中配置的音量值
*
* @return 0 on success, negative error on failure.
*/
int aos_set_master_volume(int volume);
/**
* 获取声卡中名为“Master Volume TX”的属性的值,并保存在volume指针中
*
* @param[out] *volume 获取到声卡音量值后保存到volume指针中
*
* @return 0 on success, negative error on failure.
*/
int aos_get_master_volume(int *volume);
/**
* 设置所有声卡为mute状态,对应的属性名为“Master Mute State”
*
* @param[in] mute 1为mute状态,0为unmute状态
*
* @return 0 on success, negative error on failure.
*/
int aos_set_mute_state(int mute);
/**
* 获取声卡的mute状态,并保存在*mute指针中
*
* @param[out] *mute 返回1为mute状态,0为unmute状态
*
* @return 0 on success, negative error on failure.
*/
int aos_get_mute_state(int *mute);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* SOUND_CONTROL_H */ | YifuLiu/AliOS-Things | components/a2sa/include/sound_mixer.h | C | apache-2.0 | 3,771 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef SOUND_PCM_H
#define SOUND_PCM_H
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <aos/list.h>
#include <aos/kernel.h>
#ifndef HAAS_AUDIO_DEMO
#include <sys/ioctl.h>
#endif
#include "audio_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @defgroup a2sa_pcm_api pcm
* @ingroup a2sa_api
* @{
*/
typedef unsigned long aos_pcm_uframes_t;
typedef signed long aos_pcm_sframes_t;
/* AOS_PCM常用宏定义 */
#define AOS_PCM_BLOCK 0x00000000 /**< Blocking mode (flag for open mode) */
#define AOS_PCM_NONBLOCK 0x00000001 /**< Non blocking mode (flag for open mode) */
#define AOS_PCM_ASYNC 0x00000002 /**< Async notification (flag for open mode) */
#define AOS_PCM_ABORT 0x00008000 /**< In an abort state (internal, not allowed for open) */
#define AOS_PCM_NO_AUTO_RESAMPLE 0x00010000 /**< Disable automatic (but not forced!) rate resamplinig */
#define AOS_PCM_NO_AUTO_CHANNELS 0x00020000 /**< Disable automatic (but not forced!) channel conversion */
#define AOS_PCM_NO_AUTO_FORMAT 0x00040000 /**< Disable automatic (but not forced!) format conversion */
#define AOS_PCM_NO_SOFTVOL 0x00080000 /**< Disable soft volume control */
#define AOS_PCM_EVT_WRITE (1 << 0) /**< playback resource available event */
#define AOS_PCM_EVT_READ (1 << 1) /**< capture data available event */
#define AOS_PCM_EVT_XRUN (1 << 2) /**< underrun (playback) or overrun (capture) detected */
/* PCM stream 类型定义 */
typedef enum {
AOS_PCM_STREAM_PLAYBACK = 0, /**< Playback stream */
AOS_PCM_STREAM_CAPTURE, /**< Capture stream */
AOS_PCM_STREAM_LAST = AOS_PCM_STREAM_CAPTURE
} aos_pcm_stream_t;
/* PCM stream 状态定义 */
typedef enum {
AOS_PCM_STATE_IDLE = 0, /**< IDLE */
AOS_PCM_STATE_OPEN, /**< Open */
AOS_PCM_STATE_PREPARED, /**< Ready to start */
AOS_PCM_STATE_RUNNING, /**< Running */
AOS_PCM_STATE_XRUN, /**< Stopped: underrun (playback) or overrun (capture) detected */
AOS_PCM_STATE_DRAINING, /**< Draining: running (playback) or stopped (capture) */
AOS_PCM_STATE_PAUSED, /**< Paused */
AOS_PCM_STATE_SUSPENDED, /**< Hardware is suspended */
AOS_PCM_STATE_DISCONNECTED, /**< Hardware is disconnected */
AOS_PCM_STATE_LAST = AOS_PCM_STATE_DISCONNECTED, /**< Last state */
AOS_PCM_STATE_PRIVATE1 = 1024 /**< Private - used internally in the library - do not use*/
} aos_pcm_state_t;
/* PCM stream 格式定义 */
typedef enum {
AOSRV_PCM_FORMAT_S8 = 1, /**< Signed 8-bit */
AOSRV_PCM_FORMAT_S16_LE = 2, /**< Signed 16-bit, little endian */
AOSRV_PCM_FORMAT_S24_LE = 3, /**< Signed 24-bit, little endian */
AOSRV_PCM_FORMAT_S32_LE = 4, /**< Signed 32-bit, little endian */
AOSRV_PCM_FORMAT_ALL
} aos_pcm_format_t;
/* PCM stream 访问模式定义 */
typedef enum {
AOS_PCM_ACCESS_MMAP_INTERLEAVED = 0, /**< MMAP RW interleaved access */
AOS_PCM_ACCESS_MMAP_NONINTERLEAVED, /**< MMAP RW non-interleaved access */
AOS_PCM_ACCESS_RW_INTERLEAVED, /**< RW interleaved access, e.g. writei/readi */
AOS_PCM_ACCESS_RW_NONINTERLEAVED /**< RW non-interleaved access, e.g. writen/readn */
} aos_pcm_access_t;
/* PCM stream 硬件参数类型 */
typedef struct {
aos_pcm_access_t access; /**< aos_pcm_access_t 类型 */
aos_pcm_format_t format; /**< aos_pcm_format_t 类型 */
unsigned int sample_bits; /**< 采样精度 */
unsigned int frame_bits; /**< frame 位宽大小 */
unsigned int channels; /**< channel 通道数 */
unsigned int rate; /**< 采样率 */
unsigned int period_time;
unsigned int period_size;
unsigned int period_bytes;
unsigned int periods;
unsigned int buffer_time;
unsigned int buffer_size;
unsigned int buffer_bytes;
unsigned int tick_time;
} aos_pcm_hw_params_t;
/* PCM stream 软件参数类型 */
typedef struct {
int tstamp_mode; /*< timestamp mode */
unsigned int period_step;
unsigned int sleep_min; /*< min ticks to sleep */
aos_pcm_uframes_t avail_min; /*< min avail frames for wakeup */
aos_pcm_uframes_t xfer_align; /*< obsolete: xfer size need to be a multiple */
aos_pcm_uframes_t start_threshold; /*< min hw_avail frames for automatic start */
aos_pcm_uframes_t stop_threshold; /*< min avail frames for automatic stop */
aos_pcm_uframes_t silence_threshold; /*< min distance from noise for silence filling */
aos_pcm_uframes_t silence_size; /*< silence block size */
aos_pcm_uframes_t boundary; /*< pointers wrap point */
unsigned int proto; /*< protocol version */
unsigned int tstamp_type; /*< timestamp type (req. proto >= 2.0.12) */
unsigned char reserved[56]; /*< reserved for future */
} aos_pcm_sw_params_t;
/* PCM stream 类型 */
typedef struct {
/* mandatory */
int fd; /*< 该pcm设备节点的fd,通过open()获取 */
aos_pcm_stream_t stream; /*< aos_pcm_stream_t 类型 */
aos_pcm_state_t state; /*< aos_pcm_state_t 类型 */
char *name; /*< pcm stream name */
int mode;
int card; /*< pcm stream 所属的card id */
int device; /*< pcm stream device id */
aos_hdl_t mutex;
aos_hdl_t evt;
aos_pcm_hw_params_t *hw_params; /*< pcm stream 硬件参数 */
aos_pcm_sw_params_t *sw_params; /*< pcm stream 软件参数 */
/* options */
void *open_func;
long minperiodtime;
int poll_fd_count;
unsigned short poll_events;
int setup;
int compat;
unsigned int mmap_rw: 1;
unsigned int mmap_shadow: 1;
unsigned int donot_close: 1;
unsigned int own_state_check:1;
void *private_data;
} aos_pcm_t;
/* 所有声卡的PCM stream汇总 */
typedef struct {
dlist_t list; /*< 列表 */
unsigned int count; /*< 列表中PCM Stream个数 */
unsigned int allocated;
const char *siface; /*< 默认: AOS_CTL_ELEM_IFACE_MIXER */
int card; /*< 当前声卡ID */
int device; /*< 在当前声中的设备ID */
long device_input;
long device_output;
int stream; /*< 0: Capture Stream 类型,1: Playback Stream 类型 */
int show_all;
char name[100]; /*< 当前设备名 */
} hint_list_t;
/**
* 获取声卡card下属所有的PCM Stream
*
* @param[in] card 声卡ID
* @param[out] hints hint_list_t类型列表
*
* @return 0 on success, negative error on failure.
*/
int aos_device_name_hint(int card, void *hints);
/**
* 获取声卡card下属所有的PCM Stream
*
* @param[out] **pcm aos_pcm_t 句柄指针
* @param[in] *name pcm stream name
* @param[in] stream aos_pcm_stream_t 类型
* @param[in] mode AOS_PCM_BLOCK 或者 AOS_PCM_NONBLOCK
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_open(aos_pcm_t **pcm, const char *name, aos_pcm_stream_t stream, int mode);
/**
* 设置PCM Stream为prepared状态
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_prepare(aos_pcm_t *pcm);
/**
* 设置PCM Stream为START状态
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_start(aos_pcm_t *pcm);
/**
* 设置PCM Stream为wait状态, 最大超时时间timeout milisecond
*
* @param[in] *pcm aos_pcm_t 句柄
* @param[in] timeout 超时时间,毫秒为单位
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_wait(aos_pcm_t *pcm, int timeout);
/**
* 停止PCM Stream
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_stop(aos_pcm_t *pcm);
/**
* 等待Playback PCM Stream buffer中的数据播放完成
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_drain(aos_pcm_t *pcm);
/**
* 暂停 PCM Stream
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_pause(aos_pcm_t *pcm, int enable);
/**
* 关闭 PCM Stream
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_close(aos_pcm_t *pcm);
/**
* 恢复 PCM Stream 底层硬件状态(可选)
*
* @param[in] *pcm aos_pcm_t 句柄
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_recover(aos_pcm_t *pcm);
/**
* 分配 aos_pcm_hw_params_t 类型缓存区
*
* @param[out] **p aos_pcm_hw_params_t 类型2级指针
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_hw_params_alloca(aos_pcm_hw_params_t **p);
/**
* 设置aos_pcm_hw_params_t 类型参数为默认参数
*
* @param[in] *params aos_pcm_hw_params_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_hw_params_any(aos_pcm_hw_params_t *params);
/**
* 设置pcm stream的硬件参数为 *p 指向的参数
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *p aos_pcm_hw_params_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_hw_params(aos_pcm_t *pcm, aos_pcm_hw_params_t *p);
/**
* 根据输入参数设置pcm stream的硬件参数
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] format aos_pcm_format_t 类型
* @param[in] access aos_pcm_access_t 类型
* @param[in] channels unsigned int 类型, 通道数
* @param[in] rate unsigned int 类型, 采样率
* @param[in] soft_resample int 类型
* @param[in] latency unsigned int 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_set_params(aos_pcm_t *pcm, aos_pcm_format_t format, aos_pcm_access_t access, unsigned int channels,
unsigned int rate, int soft_resample, unsigned int latency);
/**
* 分配 aos_pcm_sw_params_t 类型缓存区
*
* @param[in] **p aos_pcm_sw_params_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_sw_params_alloca(aos_pcm_sw_params_t **p);
/**
* 设置 aos_pcm_sw_params_t 类型参数为默认参数
*
* @param[in] *params aos_pcm_sw_params_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_sw_params_any(aos_pcm_sw_params_t *params);
/**
* 设置pcm stream的软件参数为 *params 指向的参数
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *params aos_pcm_sw_params_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_sw_params(aos_pcm_t *pcm, aos_pcm_sw_params_t *params);
/**
* 以interleave格式往pcm stream写数据(e.g. CH0 -> CH1 -> CH2 -> CH0 ...)
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *buffer 待写入的数据buffer
* @param[in] *size 待写入的数据buffer大小,以字节为单位
*
* @return writen bytes number on success, negative error on failure.
*/
aos_pcm_sframes_t aos_pcm_writei(aos_pcm_t *pcm, const void *buffer, aos_pcm_uframes_t size);
/**
* 以interleave格式从pcm stream读数据(e.g. CH0 -> CH1 -> CH2 -> CH0 ...)
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *buffer 存储读出数据的buffer
* @param[in] *size 待读出的数据大小,以字节为单位
*
* @return read bytes number on success, negative error on failure.
*/
aos_pcm_sframes_t aos_pcm_readi(aos_pcm_t *pcm, void *buffer, aos_pcm_uframes_t size);
/**
* 以non-interleave格式往pcm stream写数据(e.g. CH0 -> CH0 ...-> CH0 (size 单位数据全部写完) -> CH1 -> CH1 ...)
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *buffer 待写入的数据buffer
* @param[in] *size 待写入的数据buffer大小,以字节为单位
*
* @return writen bytes number on success, negative error on failure.
*/
aos_pcm_sframes_t aos_pcm_writen(aos_pcm_t *pcm, void **bufs, aos_pcm_uframes_t size);
/**
* 以non-interleave格式从pcm stream读数据(e.g. CH0 -> CH0 ...-> CH0 (size 单位数据全部读完) -> CH1 -> CH1 ...)
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *buffer 存储读出数据的buffer
* @param[in] *size 待读出的数据大小,以字节为单位
*
* @return read bytes number on success, negative error on failure.
*/
aos_pcm_sframes_t aos_pcm_readn(aos_pcm_t *pcm, void **bufs, aos_pcm_uframes_t size);
/**
* 暂停pcm stream,buffer中的数据仍然保留
*
* @param[in] *pcm aos_pcm_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_suspend(aos_pcm_t *pcm);
/**
* 恢复pcm stream,buffer中遗留的数据继续读写
*
* @param[in] *pcm aos_pcm_t* 类型
*
* @return 0 on success, negative error on failure.
*/
int aos_pcm_resume(aos_pcm_t *pcm);
/**
* 根据pcm stream的参数配置计算bytes个字节对应的frame帧数
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] bytes 字节数
*
* @return aos_pcm_sframes_t on success, negative error on failure.
*/
aos_pcm_sframes_t aos_pcm_bytes_to_frames(aos_pcm_t *pcm, int bytes);
/**
* 根据pcm stream的参数配置计算frame帧数对应的bytes字节数
*
* @param[in] *pcm aos_pcm_t* 类型
* @param[in] *frames 帧数
*
* @return unsigned int on success, negative error on failure.
*/
int aos_pcm_frames_to_bytes(aos_pcm_t *pcm, aos_pcm_sframes_t frames);
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* SOUND_PCM_H */
| YifuLiu/AliOS-Things | components/a2sa/include/sound_pcm.h | C | apache-2.0 | 14,675 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef AUDIO_CARD_H
#define AUDIO_CARD_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <aos/list.h>
#include "control_dev.h"
#include "pcm_dev.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int id;
struct dlist_s pcm_dev_list; /* pcm device list */
int pcm_dev_num; /* pcm device num */
int pcm_str_num;
ctrl_device_t *ctrl_dev; /* ctrl device list */
} audio_card_t;
audio_card_t *audio_card_new();
pcm_device_t * audio_card_get_pcm_device(audio_card_t *card, void *private_data);
int audio_card_add_pcm_dev(audio_card_t *card, pcm_device_t *pcm_dev);
int audio_card_remove_pcm_dev(audio_card_t *card, pcm_device_t *pcm_dev);
int audio_card_remove(audio_card_t *card);
#ifdef __cplusplus
}
#endif
#endif /* AUDIO_CARD_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/core/audio_card.h | C | apache-2.0 | 857 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef AUDIO_H
#define AUDIO_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <aos/vfs.h>
#include <aos/list.h>
#include <aos/kernel.h>
#include "control.h"
#ifdef __cplusplus
extern "C" {
#endif
#define _IOC_NONE 0U /**< 0x00 */
#define _IOC_WRITE 1U /**< 0x01 */
#define _IOC_READ 2U /**< 0x02 */
#define _IOC_TYPECHECK(t) (sizeof(t))
#define _IOC(dir,type,nr,size) (((dir) << 30) | \
((size) << 16) | \
((type) << 8) | \
((nr) << 0))
/* audio device type */
#define AUDIO_DEVICE_TYPE_PCM_CAPTURE 0
#define AUDIO_DEVICE_TYPE_PCM_PLAYBACK 1
#define AUDIO_DEVICE_TYPE_CONTROL 2
/* pcm device ioctl */
#define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0)
#define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size)))
#define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
#define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size)))
#define AUDIO_PCM_IOCTL_HW_PARAMS _IOWR('A', 0x11, audio_hw_params_t)
#define AUDIO_PCM_IOCTL_SW_PARAMS _IOWR('A', 0x12, audio_sw_params_t)
#define AUDIO_PCM_IOCTL_PREPARE _IO('A', 0x40)
#define AUDIO_PCM_IOCTL_START _IO('A', 0x42)
#define AUDIO_PCM_IOCTL_WRITEI_FRAMES _IOW('A', 0x50, audio_xferi_t)
#define AUDIO_PCM_IOCTL_READI_FRAMES _IOR('A', 0x51, audio_xferi_t)
#define AUDIO_PCM_IOCTL_WRITEN_FRAMES _IOW('A', 0x52, audio_xfern_t)
#define AUDIO_PCM_IOCTL_READN_FRAMES _IOR('A', 0x53, audio_xfern_t)
#define AUDIO_PCM_IOCTL_DROP _IO('A', 0x43) /* looks like only for read */
#define AUDIO_PCM_IOCTL_DRAIN _IO('A', 0x44)
#define AUDIO_PCM_IOCTL_PAUSE _IOW('A', 0x45, int)
#define AUDIO_PCM_IOCTL_SUSPEND _IO('A', 0x46)
#define AUDIO_PCM_IOCTL_RESUME _IO('A', 0x47)
#define AUDIO_PCM_IOCTL_RECOVER _IO('A', 0x80) /* aos private */
/* mixer virtual device ioctl */
#define AUDIO_CTL_IOCTL_CARD_INFO _IOR('U', 0x01, struct audio_ctl_card_info)
#define AUDIO_CTL_IOCTL_ELEM_LIST _IOWR('U', 0x10, struct audio_ctl_elem_list)
#define AUDIO_CTL_IOCTL_ELEM_INFO _IOWR('U', 0x11, struct audio_ctl_elem_info)
#define AUDIO_CTL_IOCTL_ELEM_READ _IOWR('U', 0x12, struct audio_ctl_elem_value)
#define AUDIO_CTL_IOCTL_ELEM_WRITE _IOWR('U', 0x13, struct audio_ctl_elem_value)
#define AUDIO_CTL_IOCTL_TLV_READ _IOWR('U', 0x1a, struct audio_ctl_tlv)
#define AUDIO_CTL_IOCTL_TLV_WRITE _IOWR('U', 0x1b, struct audio_ctl_tlv)
#define AUDIO_CTL_IOCTL_TLV_CMD _IOWR('U', 0x1c, struct audio_ctl_tlv)
#define RET_ERR -1
#define RET_SUCCESS 0
typedef struct {
int block; /**< 0: non-block mode, otherwise block mode, */
int interleave; /**< 0: non-interleave access, otherwise interleave access, */
int rate; /**< sample rate, e.g. 8KHz, 16KHz */
int channels; /**< channel number, e.g. CH1/ CH2 */
int sample_bits; /**< sample size in bit */
} audio_hw_params_t;
typedef struct {
aos_hdl_t *hdl; /**< aos_event_t handler pointer */
int period; /**< sample size in bit */
} audio_sw_params_t;
typedef struct {
int result; /**< transfer result, 0/ SUCCESS, otherwise FAILED */
void *buf; /**< data buffer */
unsigned int frames; /**< data buffer size in frame */
} audio_xferi_t;
typedef struct {
int result; /**< transfer result, 0/ SUCCESS, otherwise FAILED */
void **bufs; /**< data buffer */
unsigned int frames; /**< data buffer size in frame */
} audio_xfern_t;
typedef struct {
struct dlist_s list; /**< audio device node */
int type; /**< audio device type */
char *name; /**< transfer result, 0/ SUCCESS, otherwise FAILED */
file_ops_t *f_ops; /**< file operations */
void *private_data; /**< private data buffer */
} audio_device_t;
int audio_register_device(int type, const char *name, void *private_data);
int audio_unregister_device(audio_device_t *dev);
audio_device_t *audio_get_device(const char *name);
#ifdef __cplusplus
}
#endif
#endif /* AUDIO_H */
| YifuLiu/AliOS-Things | components/a2sa/internal/driver/core/audio_drv.h | C | apache-2.0 | 4,859 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef CONTROL_H
#define CONTROL_H
#include <stdio.h>
#include <aos/list.h>
#include "control_dev.h"
#ifdef __cplusplus
extern "C" {
#endif
struct audio_kcontrol;
struct audio_mixer_control;
#define AOS_CTL_ELEM_TYPE_NONE (1 << 0) /* invalid */
#define AOS_CTL_ELEM_TYPE_BOOLEAN (1 << 1) /* boolean type */
#define AOS_CTL_ELEM_TYPE_INTEGER (1 << 2) /* integer type */
#define AOS_CTL_ELEM_TYPE_ENUMERATED (1 << 3) /* enumerated type */
#define AOS_CTL_ELEM_TYPE_BYTES (1 << 4) /* byte array */
#define AOS_CTL_ELEM_TYPE_IEC958 (1 << 5) /* IEC958 (S/PDIF) setup */
#define AOS_CTL_ELEM_TYPE_INTEGER64 (1 << 6) /* 64-bit integer type */
#define AOS_CTL_ELEM_TYPE_LAST AOS_CTL_ELEM_TYPE_INTEGER64
#define AOS_CTL_ELEM_IFACE_MIXER (1 << 2) /* virtual mixer device */
#define AOS_CTL_ELEM_IFACE_LAST AOS_CTL_ELEM_IFACE_MIXER
#define AOS_CTL_ELEM_ACCESS_READ (1<<0)
#define AOS_CTL_ELEM_ACCESS_WRITE (1<<1)
#define AOS_CTL_ELEM_ACCESS_READWRITE (AOS_CTL_ELEM_ACCESS_READ|AOS_CTL_ELEM_ACCESS_WRITE)
#define AOS_DOUBLE_VALUE(sreg, left, right, smax, sinvert, sautodisable) \
((unsigned long)&(struct audio_mixer_control) \
{.reg = sreg, .rreg = sreg, .shift = left, \
.rshift = right, .max = smax, .platform_max = smax, \
.invert = sinvert, .autodisable = sautodisable})
#define AOS_SINGLE_VALUE(reg, shift, max, invert, autodisable) \
AOS_DOUBLE_VALUE(reg, shift, shift, max, invert, autodisable)
#define SOC_SINGLE_EXT(sname, reg, shift, max, invert, handler_get, handler_put) \
{ .iface = AOS_CTL_ELEM_IFACE_MIXER, \
.name = sname, \
.info = get_integer_info, \
.get = handler_get, \
.put = handler_put, \
.private_value = AOS_SINGLE_VALUE(reg, shift, max, invert, 0) \
}
#define SOC_DOUBLE_EXT(sname, reg, left, right, max, invert, handler_get, handler_put) \
{ .iface = AOS_CTL_ELEM_IFACE_MIXER, \
.name = (sname),\
.info = get_integer_info, \
.get = handler_get, \
.put = handler_put, \
.private_value = AOS_DOUBLE_VALUE(reg, left, right, max, invert, 0) \
}
struct audio_ctl_card_info {
int card; /* card number */
unsigned char driverName[16]; /* Driver name */
unsigned char shortName[32]; /* Short name of card */
unsigned char longName[64]; /* long name about card */
unsigned char mixerName[64]; /* visual mixer name */
unsigned char components[64]; /* card components info */
};
struct audio_ctl_elem_id {
unsigned int id; /* element id, zero = invalid */
int iface; /* interface id */
unsigned int deviceId; /* device number */
unsigned int subdeviceId; /* subdevice (substream) number */
char name[64]; /* name of item */
unsigned int index; /* index of item */
};
struct audio_ctl_elem_list {
struct audio_ctl_elem_id *pids; /* R: IDs */
unsigned int offset; /* W: first element offset */
unsigned int space; /* W: element count to get */
unsigned int used; /* R: element count been set */
unsigned int count; /* R: total elements count */
};
struct audio_ctl_elem_info {
struct audio_ctl_elem_id id; /* W: element ID */
int type; /* R: AOS_CTL_ELEM_TYPE_* */
unsigned int access; /* R: AOS_CTL_ELEM_ACCESS_* */
unsigned int count; /* count of values */
union {
struct {
long min; /* R: min value */
long max; /* R: max value */
long step; /* R: step */
} integer;
struct {
long long min; /* R: min value */
long long max; /* R: max value */
long long step; /* R: step */
} integer64;
} value;
};
struct audio_ctl_elem_value {
struct audio_ctl_elem_id id; /* W: element ID */
union {
union {
long value[64];
} integer;
union {
long long value[64];
} integer64;
union {
unsigned char data[512];
} bytes;
} value; /* RO */
};
struct audio_ctl_tlv {
unsigned int numid; /* control element numeric identification */
unsigned int len; /* in bytes aligned to 4 */
unsigned int tlv[0]; /* first TLV */
};
/* mixer control */
typedef int (audio_kcontrol_info_t) (struct audio_kcontrol * kcontrol, struct audio_ctl_elem_info * uinfo);
typedef int (audio_kcontrol_get_t) (struct audio_kcontrol * kcontrol, struct audio_ctl_elem_value * ucontrol);
typedef int (audio_kcontrol_put_t) (struct audio_kcontrol * kcontrol, struct audio_ctl_elem_value * ucontrol);
typedef int (audio_kcontrol_tlv_rw_t)(struct audio_kcontrol *kcontrol, int op_flag, unsigned int size, unsigned int *tlv);
struct audio_mixer_control {
int min, max, platform_max;
int reg, rreg;
unsigned int shift, rshift;
unsigned int sign_bit;
unsigned int invert:1;
unsigned int autodisable:1;
};
struct audio_kcontrol_volatile {
void *owner; /* locked */
unsigned int access; /* access rights */
};
struct audio_kcontrol_new {
unsigned int iface; /* interface identifier */
const char *name; /* ASCII name of item */
audio_kcontrol_info_t *info;
audio_kcontrol_get_t *get;
audio_kcontrol_put_t *put;
union {
audio_kcontrol_tlv_rw_t *c;
const unsigned int *p;
} tlv;
unsigned long private_value;
unsigned int deviceId; /* device ID*/
unsigned int subdeviceId; /* subdevice ID */
unsigned int index; /* index of item */
unsigned int access; /* access rights */
unsigned int count; /* count of same elements */
};
struct audio_kcontrol {
struct dlist_s list; /* list of controls */
struct audio_ctl_elem_id id;
unsigned int count; /* count of same elements */
audio_kcontrol_info_t *info;
audio_kcontrol_get_t *get;
audio_kcontrol_put_t *put;
union {
audio_kcontrol_tlv_rw_t *c;
unsigned int *p;
} tlv;
unsigned long private_value;
void *private_data;
void (*private_free)(struct audio_kcontrol *kcontrol);
struct audio_kcontrol_volatile vd[0]; /* volatile data */
};
enum {
AOS_CTL_TLV_OP_READ = 0,
AOS_CTL_TLV_OP_WRITE = 1,
AOS_CTL_TLV_OP_CMD = -1,
};
int get_integer_info(struct audio_kcontrol * kcontrol, struct audio_ctl_elem_info * uinfo);
int audio_ctl_card_info(ctrl_device_t *dev, struct audio_ctl_card_info *info);
int audio_ctl_elem_list(ctrl_device_t *dev, struct audio_ctl_elem_list *list);
int audio_ctl_elem_info(ctrl_device_t *dev, struct audio_ctl_elem_info *info);
int audio_ctl_elem_read(ctrl_device_t *dev, struct audio_ctl_elem_value *value);
int audio_ctl_elem_write(ctrl_device_t *dev, struct audio_ctl_elem_value *value);
int audio_ctl_tlv_ioctl(ctrl_device_t *dev, struct audio_ctl_tlv *tlv, int op_flag);
int audio_add_controls(ctrl_device_t *dev, const struct audio_kcontrol_new *controls, int num_controls, void *data);
#ifdef __cplusplus
}
#endif
#endif /* CONTROL_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/core/control.h | C | apache-2.0 | 6,941 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef CONTROL_DEV_H
#define CONTROL_DEV_H
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <aos/list.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int id;
char name[32];
struct dlist_s kcontrol_list; /* audio_kcontrol list */
int kcontrols_count;
int last_numid;
bool ctrl_dev_state;
void *parent_data;
} ctrl_device_t;
ctrl_device_t *audio_ctrl_device_new(int id);
int audio_ctrl_device_free(ctrl_device_t *dev);
#ifdef __cplusplus
}
#endif
#endif /* CONTROL_DEV_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/core/control_dev.h | C | apache-2.0 | 590 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef PCM_DEV_H
#define PCM_DEV_H
#include <stdio.h>
#include <aos/list.h>
#include "audio_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
int (*open)(void *dev);
int (*hw_params)(void *dev, audio_hw_params_t *params);
int (*sw_params)(void *dev, audio_sw_params_t *params);
int (*hw_prepare)(void *dev);
int (*start)(void *dev);
int (*readi)(void *dev, audio_xferi_t *xbuf);
int (*writei)(void *dev, audio_xferi_t *xbuf);
int (*readn)(void *dev, audio_xfern_t *xbuf);
int (*writen)(void *dev, audio_xfern_t *xbuf);
int (*drain)(void *dev);
int (*pause)(void *dev, int enable);
int (*stop)(void *dev);
int (*close)(void *dev);
int (*recover)(void *dev);
int (*suspend)(void *dev);
int (*resume)(void *dev);
} pcm_device_ops_t;
typedef struct {
int dirType;
char *name;
audio_hw_params_t hwParams;
pcm_device_ops_t *ops;
audio_device_t *audioDevice;
void *private_data;
struct dlist_s list;
} pcm_device_t;
pcm_device_t *audio_pcm_device_new(int dirType, const char *name, pcm_device_ops_t *ops, void *private_data);
int audio_pcm_device_free(pcm_device_t *dev);
#ifdef __cplusplus
}
#endif
#endif /* PCM_DEV_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/core/pcm_dev.h | C | apache-2.0 | 1,293 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef AUDIO_RTOS_H
#define AUDIO_RTOS_H
#include <stdio.h>
#include <stdbool.h>
#include "audio_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef void* pcm_stream_handler_t;
typedef enum {
PCM_STREAM_IN = 0,
PCM_STREAM_OUT = 1,
} pcm_stream_dir_t;
typedef enum {
/** Signed, 8-bit */
PCM_STREAM_FORMAT_S8 = 1,
/** Signed 16-bit, little endian */
PCM_STREAM_FORMAT_S16_LE = 0,
/** Signed, 16-bit, big endian */
PCM_STREAM_FORMAT_S16_BE = 2,
/** Signed, 24-bit (32-bit in memory), little endian */
PCM_STREAM_FORMAT_S24_LE,
/** Signed, 24-bit (32-bit in memory), big endian */
PCM_STREAM_FORMAT_S24_BE,
/** Signed, 24-bit, little endian */
PCM_STREAM_FORMAT_S24_3LE,
/** Signed, 24-bit, big endian */
PCM_STREAM_FORMAT_S24_3BE,
/** Signed, 32-bit, little endian */
PCM_STREAM_FORMAT_S32_LE,
/** Signed, 32-bit, big endian */
PCM_STREAM_FORMAT_S32_BE,
/** Max of the enumeration list, not an actual format. */
PCM_STREAM_FORMAT_MAX
} pcm_stream_format_t;
typedef struct {
pcm_stream_handler_t (*open)(int mode, int sampleRate, int channels, int format, aos_hdl_t *event_hdl);
int (*start)(pcm_stream_handler_t hdl);
int (*write)(pcm_stream_handler_t hdl, void *buf, unsigned int len);
int (*read)(pcm_stream_handler_t hdl, void *buf, unsigned int len);
int (*pause)(pcm_stream_handler_t hdl, int enable);
int (*stop)(pcm_stream_handler_t hdl);
int (*close)(pcm_stream_handler_t hdl);
int (*recover)(pcm_stream_handler_t hdl);
int (*suspend)(pcm_stream_handler_t hdl);
int (*resume)(pcm_stream_handler_t hdl);
} pcm_stream_ops_t;
typedef struct {
pcm_stream_dir_t mode;
audio_hw_params_t params;
audio_sw_params_t swParams;
bool isOpenState;
pcm_stream_ops_t *ops;
pcm_stream_handler_t hdl;
void *parent_data;
} native_pcm_device_t;
int audio_native_card_register(int rec_num, int spk_num, pcm_stream_ops_t *ops, const struct audio_kcontrol_new *controls, int controls_num);
#ifdef __cplusplus
}
#endif
#endif /* AUDIO_RTOS_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/platform/rtos/audio_rtos.h | C | apache-2.0 | 2,162 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef CAP_TASK_H
#define CAP_TASK_H
#include <stdio.h>
#include <stdbool.h>
#include "audio_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
void capture_task_start(void *dev);
void capture_task_stop();
int capture_read_data(void *dev, char *buf, unsigned int len, int blockMode);
#ifdef __cplusplus
}
#endif
#endif /* PB_TASK_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/platform/rtos/cap_task.h | C | apache-2.0 | 400 |
/*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*/
#ifndef PB_TASK_H
#define PB_TASK_H
#include <stdio.h>
#include <stdbool.h>
#include "audio_drv.h"
#ifdef __cplusplus
extern "C" {
#endif
void playback_task_start();
void playback_task_stop();
int playback_push_data(void *dev, const char *buf, unsigned int len, int blockMode);
int playback_task_drain();
#ifdef __cplusplus
}
#endif
#endif /* PB_TASK_H */ | YifuLiu/AliOS-Things | components/a2sa/internal/driver/platform/rtos/pb_task.h | C | apache-2.0 | 425 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <aos/kernel.h>
#include <aos/vfs.h>
#include <ulog/ulog.h>
#include "audio_drv.h"
#include "pcm_dev.h"
#include "control.h"
#include "control_dev.h"
#define LOG_TAG "[audio]"
#define AUDIO_DEVICE_NAME_LEN 50
AOS_DLIST_HEAD(dev_head);
static int audio_pcm_open(inode_t *inode, file_t *file)
{
int ret = RET_ERR;
pcm_device_t *pcm = NULL;
audio_device_t *dev = NULL;
if(!inode || !file) {
LOGE(LOG_TAG, "%s:%d, inode is null", __func__, __LINE__);
return -EINVAL;
}
dev = audio_get_device(inode->i_name);
if(!dev) {
LOGE(LOG_TAG, "%s:%d, not found audio device", __func__, __LINE__);
return -EINVAL;
}
pcm = (pcm_device_t *)(dev->private_data);
if(!pcm || !pcm->ops) {
LOGE(LOG_TAG, "%s:%d, private_date is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm->ops->open(pcm->private_data);
LOGD(LOG_TAG, "%s:%d, open audio dev %s %s", __func__, __LINE__, inode->i_name, (ret == RET_SUCCESS)? "success" : "failed");
return ret;
}
static int audio_pcm_close(file_t *file)
{
int ret = RET_ERR;
pcm_device_t *pcm = NULL;
audio_device_t *dev = NULL;
if(!file) {
LOGE(LOG_TAG, "%s:%d, file is null", __func__, __LINE__);
return -EINVAL;
}
if(!file->node) {
LOGE(LOG_TAG, "%s:%d, file->node is null", __func__, __LINE__);
return -EINVAL;
}
dev = audio_get_device(file->node->i_name);
if(!dev) {
LOGE(LOG_TAG, "%s:%d, not found audio device", __func__, __LINE__);
return -EINVAL;
}
pcm = (pcm_device_t *)(dev->private_data);
if (!pcm || !pcm->ops) {
LOGE(LOG_TAG, "%s:%d, private_date is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm->ops->close(pcm->private_data);
return ret;
}
static inline inode_t *file_inode(const file_t *file)
{
return file->node;
}
static int audio_pcm_ioctl(file_t *file, int cmd, unsigned long arg)
{
int ret = RET_ERR;
pcm_device_t *pcm = NULL;
audio_device_t *dev = NULL;
inode_t *inode = NULL;
if(!file) {
LOGE(LOG_TAG, "%s:%d, file is null.", __func__, __LINE__);
return -EINVAL;
}
inode = file->node;
if (!inode) {
LOGE(LOG_TAG, "%s:%d, inode is null.", __func__, __LINE__);
return -EINVAL;
}
dev = audio_get_device(inode->i_name);
if (!dev) {
LOGE(LOG_TAG, "%s:%d, no matched device", __func__, __LINE__);
return -EINVAL;
}
pcm = (pcm_device_t *)(dev->private_data);
if (!pcm || !pcm->ops) {
LOGE(LOG_TAG, "%s:%d, private_date is null", __func__, __LINE__);
return -EINVAL;
}
switch (cmd) {
case AUDIO_PCM_IOCTL_HW_PARAMS:
ret = pcm->ops->hw_params(pcm->private_data, (audio_hw_params_t *)arg);
break;
case AUDIO_PCM_IOCTL_SW_PARAMS:
ret = pcm->ops->sw_params(pcm->private_data, (audio_sw_params_t *)arg);
break;
case AUDIO_PCM_IOCTL_PREPARE:
ret = pcm->ops->hw_prepare(pcm->private_data);
break;
case AUDIO_PCM_IOCTL_START:
ret = pcm->ops->start(pcm->private_data);
break;
case AUDIO_PCM_IOCTL_READI_FRAMES:
ret = pcm->ops->readi(pcm->private_data, (audio_xferi_t *)arg);
break;
case AUDIO_PCM_IOCTL_READN_FRAMES:
ret = pcm->ops->readn(pcm->private_data, (audio_xfern_t *)arg);
break;
case AUDIO_PCM_IOCTL_WRITEI_FRAMES:
ret = pcm->ops->writei(pcm->private_data, (audio_xferi_t *)arg);
break;
case AUDIO_PCM_IOCTL_WRITEN_FRAMES:
ret = pcm->ops->writen(pcm->private_data, (audio_xfern_t *)arg);
break;
case AUDIO_PCM_IOCTL_DROP:
ret = pcm->ops->stop(pcm->private_data);
break;
case AUDIO_PCM_IOCTL_DRAIN:
ret = pcm->ops->drain(pcm->private_data);
break;
case AUDIO_PCM_IOCTL_PAUSE:
ret = pcm->ops->pause(pcm->private_data, (int)arg);
break;
case AUDIO_PCM_IOCTL_SUSPEND:
ret = pcm->ops->suspend(pcm->private_data);
break;
case AUDIO_PCM_IOCTL_RESUME:
ret = pcm->ops->resume(pcm->private_data);
break;
case AUDIO_PCM_IOCTL_RECOVER:
ret = pcm->ops->recover(pcm->private_data);
break;
default:
break;
}
//LOGD(LOG_TAG, "%s:%d, ioctl audio dev %s %s", __func__, __LINE__, inode->i_name, (ret == RET_SUCCESS)? "success" : "failed");
return ret;
}
static int audio_ctrl_open(inode_t *inode, file_t *file)
{
ctrl_device_t *ctrl = NULL;
audio_device_t *dev = NULL;
if (!inode || !file) {
LOGE(LOG_TAG, "%s:%d, inode is null", __func__, __LINE__);
return -EINVAL;
}
dev = audio_get_device(inode->i_name);
if (!dev) {
LOGE(LOG_TAG, "%s:%d, no matched device", __func__, __LINE__);
return -EINVAL;
}
ctrl = (ctrl_device_t *)(dev->private_data);
if (!ctrl) {
LOGE(LOG_TAG, "%s:%d, ctrl dev is null", __func__, __LINE__);
return -EINVAL;
}
if (true == ctrl->ctrl_dev_state) {
LOGE(LOG_TAG, "%s:%d, ctrl device already opened", __func__, __LINE__);
return -EACCES;
}
ctrl->ctrl_dev_state = true;
LOGD(LOG_TAG, "%s:%d, open device %s successfully!!", __func__, __LINE__, inode->i_name);
return RET_SUCCESS;
}
static int audio_ctrl_close(file_t *file)
{
int ret = RET_SUCCESS;
ctrl_device_t *ctrl = NULL;
audio_device_t *dev = NULL;
if (!file) {
LOGE(LOG_TAG, "%s:%d, file is null", __func__, __LINE__);
return -EINVAL;
}
if (!file->node) {
LOGE(LOG_TAG, "%s:%d, file->node is null", __func__, __LINE__);
return -EINVAL;
}
dev = audio_get_device(file->node->i_name);
if (!dev) {
LOGE(LOG_TAG, "%s:%d, no matched device", __func__, __LINE__);
return -EINVAL;
}
ctrl = (ctrl_device_t *)(dev->private_data);
if (!ctrl) {
LOGE(LOG_TAG, "%s:%d, ctrl dev is null", __func__, __LINE__);
return -EINVAL;
}
if (false == ctrl->ctrl_dev_state) {
LOGE(LOG_TAG, "%s:%d, ctrl device already closed", __func__, __LINE__);
return -EACCES;
}
ctrl->ctrl_dev_state = false;
LOGD(LOG_TAG, "%s:%d, close audio dev %s %s", __func__, __LINE__, file->node->i_name, (ret == RET_SUCCESS)? "success" : "failed");
return ret;
}
static int audio_ctrl_ioctl(file_t *file, int cmd, unsigned long arg)
{
int ret = -1;
ctrl_device_t *ctrl = NULL;
audio_device_t *dev = NULL;
inode_t *inode = NULL;
if (!file) {
LOGE(LOG_TAG, "%s:%d, file is null.", __func__, __LINE__);
return -EINVAL;
}
inode = file->node;
if (!inode) {
LOGE(LOG_TAG, "%s:%d, inode is null.", __func__, __LINE__);
return -EINVAL;
}
dev = audio_get_device(inode->i_name);
if (!dev) {
LOGE(LOG_TAG, "%s:%d, no matched device", __func__, __LINE__);
return -EINVAL;
}
ctrl = (ctrl_device_t *)(dev->private_data);
if (!ctrl) {
LOGE(LOG_TAG, "%s:%d, private_data is null", __func__, __LINE__);
return -EINVAL;
}
switch (cmd) {
case AUDIO_CTL_IOCTL_CARD_INFO:
ret = audio_ctl_card_info(ctrl, (struct audio_ctl_card_info *)arg);
break;
case AUDIO_CTL_IOCTL_ELEM_LIST:
ret = audio_ctl_elem_list(ctrl, (struct audio_ctl_elem_list *)arg);
break;
case AUDIO_CTL_IOCTL_ELEM_INFO:
ret = audio_ctl_elem_info(ctrl, (struct audio_ctl_elem_info *)arg);
break;
case AUDIO_CTL_IOCTL_ELEM_READ:
ret = audio_ctl_elem_read(ctrl, (struct audio_ctl_elem_value *)arg);
break;
case AUDIO_CTL_IOCTL_ELEM_WRITE:
ret = audio_ctl_elem_write(ctrl, (struct audio_ctl_elem_value *)arg);
break;
case AUDIO_CTL_IOCTL_TLV_READ:
ret = audio_ctl_tlv_ioctl(ctrl, (struct audio_ctl_tlv *)arg, AOS_CTL_TLV_OP_READ);
break;
case AUDIO_CTL_IOCTL_TLV_WRITE:
ret = audio_ctl_tlv_ioctl(ctrl, (struct audio_ctl_tlv *)arg, AOS_CTL_TLV_OP_WRITE);
break;
case AUDIO_CTL_IOCTL_TLV_CMD:
ret = audio_ctl_tlv_ioctl(ctrl, (struct audio_ctl_tlv *)arg, AOS_CTL_TLV_OP_CMD);
break;
default:
LOGD(LOG_TAG, "%s:%d, unsupported cmd 0x%x", __func__, __LINE__, cmd);
break;
}
//LOGD(LOG_TAG, "%s:%d, file path %s, cmd 0x%x", __func__, __LINE__, inode->i_name, cmd);
return ret;
}
file_ops_t audio_fops[2] = {
{
.open = audio_pcm_open,
.close = audio_pcm_close,
.ioctl = audio_pcm_ioctl,
},
{
.open = audio_ctrl_open,
.close = audio_ctrl_close,
.ioctl = audio_ctrl_ioctl,
},
};
int audio_register_device(int type, const char *name, void *private_data)
{
int ret = RET_ERR;
audio_device_t *new_dev = NULL, *node = NULL;
if (!name || !private_data) {
LOGE(LOG_TAG, "%s:%d, invalid name or private_data.", __func__, __LINE__);
return -EINVAL;
}
if ((type < AUDIO_DEVICE_TYPE_PCM_CAPTURE) || (type > AUDIO_DEVICE_TYPE_CONTROL)) {
LOGE(LOG_TAG, "%s:%d, invalid type %d.", __func__, __LINE__, type);
return -EINVAL;
}
dlist_for_each_entry(&dev_head, node, audio_device_t, list) {
if ((node->type == type) && (node->private_data == private_data)) {
LOGE(LOG_TAG, "%s:%d, adevice %d 0x%x already existed.", __func__, __LINE__, type, private_data);
return -EINVAL;
}
}
new_dev = (audio_device_t *)malloc(sizeof(audio_device_t));
if (!new_dev) {
LOGE(LOG_TAG, "%s:%d, new_dev is null.", __func__, __LINE__);
return -ENOMEM;
}
memset(new_dev, 0, sizeof(audio_device_t));
new_dev->name = strdup(name);
if (!new_dev->name) {
LOGE(LOG_TAG, "%s:%d, name is null.", __func__, __LINE__);
return -ENOMEM;
}
dlist_init(&new_dev->list);
new_dev->type = type;
new_dev->private_data = private_data;
if (type == AUDIO_DEVICE_TYPE_PCM_CAPTURE || type == AUDIO_DEVICE_TYPE_PCM_PLAYBACK) {
new_dev->f_ops = &audio_fops[0];
} else if (type == AUDIO_DEVICE_TYPE_CONTROL){
new_dev->f_ops = &audio_fops[1];
}
ret = aos_register_driver(new_dev->name, new_dev->f_ops, NULL);
if (ret < 0) {
LOGE(LOG_TAG, "%s:%d, register %s failed, ret %d", __func__, __LINE__, new_dev->name, ret);
if(new_dev->name)
free(new_dev->name);
if(new_dev)
free(new_dev);
return ret;
}
dlist_add_tail(&new_dev->list, &dev_head);
LOGD(LOG_TAG, "%s:%d, register device %s successfully", __func__, __LINE__, new_dev->name);
return RET_SUCCESS;
}
int audio_unregister_device(audio_device_t *dev)
{
audio_device_t *node = NULL;
if(!dev) {
return -EINVAL;
}
dlist_for_each_entry(&dev_head, node, audio_device_t, list) {
if (node && (node->type == dev->type) && (!strcmp(node->name, dev->name) && (node->private_data == dev->private_data))) {
dlist_del(&node->list);
aos_unregister_driver(node->name);
if (node->name)
free(node->name);
if (node->private_data)
free(node->private_data);
if (node)
free(node);
return RET_SUCCESS;
}
}
return -EINVAL;
}
audio_device_t *audio_get_device(const char *name)
{
audio_device_t *node = NULL;
if (!name) {
LOGE(LOG_TAG, "%s:%d, name is null.", __func__, __LINE__);
return NULL;
}
dlist_for_each_entry(&dev_head, node, audio_device_t, list) {
if (strcmp(node->name, name) == 0) {
return node;
}
}
LOGE(LOG_TAG, "%s:%d, not found audio device %s.", __func__, __LINE__, name);
return NULL;
} | YifuLiu/AliOS-Things | components/a2sa/src/driver/core/audio.c | C | apache-2.0 | 12,236 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <ulog/ulog.h>
#include <errno.h>
#include "audio_card.h"
#include "audio_drv.h"
#define LOG_TAG "[audio_card]"
static int audio_card_bitmap = 0;
static int audio_card_get_available_id()
{
int map = 0, id = 0;
map = audio_card_bitmap;
if(map > 0x80000000) {
return -1;
}
while(map & 0x01) {
id ++;
map = map >> 1;
}
return id;
}
static void audio_card_set_id(int id)
{
audio_card_bitmap |= (0x01 << id);
}
static void audio_card_clear_id(int id)
{
audio_card_bitmap &= ~(0x01 << id);
}
audio_card_t *audio_card_new()
{
int id = 0;
int ret = -1;
audio_card_t *card = NULL;
id = audio_card_get_available_id();
if(id < 0) {
LOGE(LOG_TAG, "%s:%d, no available card id!!!", __func__, __LINE__);
return NULL;
}
card = (audio_card_t *)malloc(sizeof(audio_card_t));
if(!card) {
LOGE(LOG_TAG, "%s:%d, malloc card failed!!!", __func__, __LINE__);
return NULL;
}
memset(card, 0, sizeof(audio_card_t));
card->id = id;
card->pcm_dev_num = 0;
card->pcm_str_num = 0;
dlist_init(&card->pcm_dev_list);
/* new control device */
card->ctrl_dev = audio_ctrl_device_new(id);
if(!card->ctrl_dev) {
free(card);
return NULL;
}
ret = audio_register_device(AUDIO_DEVICE_TYPE_CONTROL, card->ctrl_dev->name, (void *)card->ctrl_dev);
if(ret < 0) {
LOGE(LOG_TAG, "%s:%d, register control device %s failed, ret %d", __func__, __LINE__, card->ctrl_dev->name, ret);
audio_ctrl_device_free(card->ctrl_dev);
free(card);
return NULL;
}
audio_card_set_id(id);
return card;
}
pcm_device_t * audio_card_get_pcm_device(audio_card_t *card, void *private_data)
{
pcm_device_t *pcm_dev = NULL, *node = NULL;
if(!card || !private_data) {
LOGE(LOG_TAG, "%s:%d, card or private_data is null", __func__, __LINE__);
return NULL;
}
dlist_for_each_entry(&card->pcm_dev_list, node, pcm_device_t, list) {
if(node->private_data == private_data) {
pcm_dev = node;
break;
}
}
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, no matched pcm dev", __func__, __LINE__);
return NULL;
}
return pcm_dev;
}
int audio_card_add_pcm_dev(audio_card_t *card, pcm_device_t *pcm_dev)
{
int ret = -1;
if(!card || !pcm_dev) {
LOGE(LOG_TAG, "%s:%d, card or pcm_dev is null!!!", __func__, __LINE__);
return ret;
}
dlist_add_tail(&pcm_dev->list, &card->pcm_dev_list);
card->pcm_dev_num ++;
ret = audio_register_device(pcm_dev->dirType, pcm_dev->name, (void *)pcm_dev);
return ret;
}
int audio_card_remove_pcm_dev(audio_card_t *card, pcm_device_t *pcm_dev)
{
int ret = -1;
if(!card || !pcm_dev) {
LOGE(LOG_TAG, "%s:%d, card or pcm_dev is null!!!", __func__, __LINE__);
return ret;
}
if(!pcm_dev->audioDevice) {
pcm_dev->audioDevice = audio_get_device(pcm_dev->name);
}
if(!pcm_dev->audioDevice) {
LOGE(LOG_TAG, "%s:%d, pcm dev audio device is null", __func__, __LINE__);
return -EINVAL;
}
ret = audio_unregister_device(pcm_dev->audioDevice);
if(!ret) {
/* unregister pcm dev successfully */
audio_pcm_device_free(pcm_dev);
card->pcm_dev_num --;
}
return 0;
}
int audio_card_remove(audio_card_t *card)
{
int ret = -1;
pcm_device_t *pcm_dev = NULL;
if(!card) {
LOGE(LOG_TAG, "%s:%d, card is null!!!", __func__, __LINE__);
return ret;
}
if(card->ctrl_dev) {
ret = audio_ctrl_device_free(card->ctrl_dev);
}
dlist_for_each_entry(&card->pcm_dev_list, pcm_dev, pcm_device_t, list) {
if(pcm_dev) {
ret = audio_card_remove_pcm_dev(card, pcm_dev);
}
}
audio_card_clear_id(card->id);
free(card);
card = NULL;
return ret;
} | YifuLiu/AliOS-Things | components/a2sa/src/driver/core/audio_card.c | C | apache-2.0 | 4,006 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <ulog/ulog.h>
#include <errno.h>
#include <string.h>
#include "control.h"
#define LOG_TAG "[control]"
#define MAX_CONTROL_COUNT 1028
static int audio_ctl_new(struct audio_kcontrol **kctl, unsigned int count, unsigned int access)
{
unsigned int size;
unsigned int idx;
if (count == 0 || count > MAX_CONTROL_COUNT) {
return -EINVAL;
}
size = sizeof(struct audio_kcontrol) + sizeof(struct audio_kcontrol_volatile) * count;
*kctl = malloc(size);
if (!*kctl) {
return -ENOMEM;
}
(*kctl)->count = count;
for (idx = 0; idx < count; idx++) {
(*kctl)->vd[idx].access = access;
}
return 0;
}
static struct audio_kcontrol *audio_ctl_new1(const struct audio_kcontrol_new *ncontrol, void *private_data)
{
struct audio_kcontrol *kctl;
unsigned int count;
unsigned int access;
int err;
if (!ncontrol) {
LOGE(LOG_TAG, "%s:%d, ncontrol is null", __func__, __LINE__);
return NULL;
}
if (!ncontrol->info) {
LOGE(LOG_TAG, "%s:%d, control info is null", __func__, __LINE__);
return NULL;
}
count = ncontrol->count;
if (count == 0)
count = 1;
access = ncontrol->access;
if (access == 0)
access = AOS_CTL_ELEM_ACCESS_READWRITE;
access &= AOS_CTL_ELEM_ACCESS_READWRITE;
err = audio_ctl_new(&kctl, count, access);
if (err < 0) {
return NULL;
}
/* The 'numid' member is decided when calling audio_ctl_add(). */
kctl->id.iface = ncontrol->iface;
kctl->id.deviceId = ncontrol->deviceId;
kctl->id.subdeviceId = ncontrol->subdeviceId;
if (ncontrol->name) {
strlcpy((char*)kctl->id.name, (const char*)ncontrol->name, sizeof(kctl->id.name));
}
kctl->id.index = ncontrol->index;
kctl->info = ncontrol->info;
kctl->get = ncontrol->get;
kctl->put = ncontrol->put;
kctl->tlv.p = ncontrol->tlv.p;
kctl->private_value = ncontrol->private_value;
kctl->private_data = private_data;
return kctl;
}
static struct audio_kcontrol *audio_soc_cnew(const struct audio_kcontrol_new *_template, void *data, const char *long_name)
{
struct audio_kcontrol_new template;
struct audio_kcontrol *kcontrol;
memcpy(&template, _template, sizeof(template));
template.index = 0;
if (long_name) {
template.name = long_name;
}
kcontrol = audio_ctl_new1(&template, data);
return kcontrol;
}
static int audio_ctl_add(ctrl_device_t *dev, struct audio_kcontrol *kcontrol)
{
struct audio_mixer_control *private_value = NULL;
if (! kcontrol) {
return -EINVAL;
}
if (!dev || !kcontrol->info) {
LOGE(LOG_TAG, "%s:%d, card or kcontrol is null", __func__, __LINE__);
goto __error__;
}
dlist_add_tail(&kcontrol->list, &dev->kcontrol_list);
dev->kcontrols_count += kcontrol->count;
kcontrol->id.id = dev->last_numid + 1;
dev->last_numid += kcontrol->count;
LOGD(LOG_TAG, "%s:%d, ----kcontrol->count: %d", __func__, __LINE__, kcontrol->count);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->id.id: %d", __func__, __LINE__, kcontrol->id.id);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->id.index: %d", __func__, __LINE__, kcontrol->id.index);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->id.iface: %d", __func__, __LINE__, kcontrol->id.iface);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->id.name: %s", __func__, __LINE__, kcontrol->id.name);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->id.device/subdevice: %d/%d", __func__, __LINE__, kcontrol->id.deviceId, kcontrol->id.subdeviceId);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->vd[0].access: %d", __func__, __LINE__, kcontrol->vd[0].access);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->tlv.p: 0x%x", __func__, __LINE__, kcontrol->tlv.p);
private_value = (struct audio_mixer_control *)kcontrol->private_value;
if(private_value) {
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->min: 0x%x", __func__, __LINE__, private_value->min);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->max: 0x%x", __func__, __LINE__, private_value->max);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->platform_max: 0x%x", __func__, __LINE__, private_value->platform_max);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->reg: 0x%x", __func__, __LINE__, private_value->reg);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->rreg: 0x%x", __func__, __LINE__, private_value->rreg);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->shift: 0x%x", __func__, __LINE__, private_value->shift);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->rshift: 0x%x", __func__, __LINE__, private_value->rshift);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->sign_bit: 0x%x", __func__, __LINE__, private_value->sign_bit);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->invert: 0x%x", __func__, __LINE__, private_value->invert);
LOGD(LOG_TAG, "%s:%d, ----kcontrol->private_value->autodisable: 0x%x", __func__, __LINE__, private_value->autodisable);
}
return 0;
__error__:
if(kcontrol->private_free) {
kcontrol->private_free(kcontrol);
}
free(kcontrol);
return -EINVAL;
}
/**************************************************************************
** audio driver interface
**************************************************************************/
int audio_add_controls(ctrl_device_t *dev, const struct audio_kcontrol_new *controls, int num_controls, void *data)
{
int err, i;
for (i = 0; i < num_controls; i++) {
const struct audio_kcontrol_new *control = &controls[i];
err = audio_ctl_add(dev, audio_soc_cnew(control, data, control->name));
if (err < 0) {
LOGE(LOG_TAG, "%s:%d, Failed to add %s: %d", __func__, __LINE__, control->name, err);
return err;
}
}
return 0;
}
/**************************************************************************
** audio service interface
**************************************************************************/
static struct audio_kcontrol *audio_ctl_find_numid(ctrl_device_t *dev, unsigned int numid)
{
struct audio_kcontrol *kctl = NULL;
if (!dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return NULL;
}
dlist_for_each_entry(&dev->kcontrol_list, kctl, struct audio_kcontrol, list) {
if (kctl->id.id <= numid && kctl->id.id + kctl->count > numid) {
return kctl;
}
}
return NULL;
}
static struct audio_kcontrol *audio_ctl_find_id(ctrl_device_t *dev, struct audio_ctl_elem_id *id)
{
struct audio_kcontrol *kctl = NULL;
if (!dev || !id) {
LOGE(LOG_TAG, "%s:%d, dev or id is null", __func__, __LINE__);
return NULL;
}
if (id->id != 0) {
return audio_ctl_find_numid(dev, id->id);
}
dlist_for_each_entry(&dev->kcontrol_list, kctl, struct audio_kcontrol, list) {
if (kctl->id.iface != id->iface)
continue;
if (kctl->id.deviceId != id->deviceId)
continue;
if (kctl->id.subdeviceId != id->subdeviceId)
continue;
if (strncmp((const char*)kctl->id.name, (const char*)id->name, sizeof(kctl->id.name)))
continue;
if (kctl->id.index > id->index)
continue;
if (kctl->id.index + kctl->count <= id->index)
continue;
return kctl;
}
return NULL;
}
int audio_ctl_card_info(ctrl_device_t *dev, struct audio_ctl_card_info *info)
{
if (!dev || !info) {
LOGE(LOG_TAG, "%s:%d, dev or info is null", __func__, __LINE__);
return -EINVAL;
}
info->card = dev->id;
strlcpy((char*)info->shortName, (const char*)dev->name, sizeof(info->shortName));
LOGD(LOG_TAG, "%s:%d, ----audio_ctl_card_info->card: %d", __func__, __LINE__, info->card);
LOGD(LOG_TAG, "%s:%d, ----audio_ctl_card_info->shortName: %s", __func__, __LINE__, info->shortName);
return 0;
}
int audio_ctl_elem_list(ctrl_device_t *dev, struct audio_ctl_elem_list *list)
{
struct audio_kcontrol *kctl;
struct audio_ctl_elem_id *dst, *id;
unsigned int offset, space, jidx;
struct dlist_s *node;
unsigned int len = 0;
if(!dev || !list) {
LOGE(LOG_TAG, "%s:%d, dev or list is null", __func__, __LINE__);
return -EINVAL;
}
offset = list->offset;
space = list->space;
LOGD(LOG_TAG, "%s:%d, ----offset: %d, space: %d", __func__, __LINE__, offset, space);
if(space > 16384) {
LOGE(LOG_TAG, "%s:%d, unexpected space size", __func__, __LINE__);
return -ENOMEM;
}
list->count = dev->kcontrols_count;
list->used = 0;
if(space > 0) {
dst = malloc(space * sizeof(struct audio_ctl_elem_id));
if(!dst) {
LOGE(LOG_TAG, "%s:%d, dst is null", __func__, __LINE__);
return -ENOMEM;
}
/* 1. find the node by count offset */
node = dev->kcontrol_list.next;
while(node != &dev->kcontrol_list) {
if(0 == offset) {
break;
}
kctl = aos_container_of(node, struct audio_kcontrol, list);
if(offset < kctl->count) {
break;
}
offset -= kctl->count;
node = node->next;
}
/* 2. copy all kctl->id to dst[] */
id = dst;
while(space > 0 && node != &dev->kcontrol_list) {
kctl = aos_container_of(node, struct audio_kcontrol, list);
for (jidx = offset; space > 0 && jidx < kctl->count; jidx++) {
/* copy kctl->id to dst[xx] */
*id = kctl->id;
id->index += jidx;
id->id += jidx;
LOGD(LOG_TAG, "%s:%d, ----id->numid: %d", __func__, __LINE__, id->id);
LOGD(LOG_TAG, "%s:%d, ----id->index: %d", __func__, __LINE__, id->index);
LOGD(LOG_TAG, "%s:%d, ----id->iface: %d", __func__, __LINE__, id->iface);
LOGD(LOG_TAG, "%s:%d, ----id->name: %s", __func__, __LINE__, id->name);
LOGD(LOG_TAG, "%s:%d, ----id->device/subdevice: %d/%d", __func__, __LINE__, id->deviceId, id->subdeviceId);
id++;
space--;
list->used++;
}
node = node->next;
offset = 0;
}
/* 3. copy dst[] to list */
if (space * sizeof(struct audio_ctl_elem_id) > list->used * sizeof(struct audio_ctl_elem_id)) {
len = list->used * sizeof(struct audio_ctl_elem_id);
} else {
len = space * sizeof(struct audio_ctl_elem_id);
}
memcpy(list->pids, dst, len);
}
return 0;
}
int audio_ctl_elem_info(ctrl_device_t *dev, struct audio_ctl_elem_info *info)
{
int ret = -1;
struct audio_kcontrol *kctl = NULL;
if(!dev || !info) {
LOGE(LOG_TAG, "%s:%d, dev or info is null", __func__, __LINE__);
return -EINVAL;
}
kctl = audio_ctl_find_id(dev, &info->id);
if(!kctl) {
LOGE(LOG_TAG, "%s:%d, no matched kctl", __func__, __LINE__);
return -ENOENT;
}
if(kctl->info) {
ret = kctl->info(kctl, info);
}
LOGD(LOG_TAG, "%s:%d, ----id->numid: %d", __func__, __LINE__, info->id.id);
LOGD(LOG_TAG, "%s:%d, ----id->index: %d", __func__, __LINE__, info->id.index);
LOGD(LOG_TAG, "%s:%d, ----id->iface: %d", __func__, __LINE__, info->id.iface);
LOGD(LOG_TAG, "%s:%d, ----id->name: %s", __func__, __LINE__, info->id.name);
return ret;
}
int audio_ctl_elem_read(ctrl_device_t *dev, struct audio_ctl_elem_value *value)
{
int ret = -1;
struct audio_kcontrol *kctl;
struct audio_kcontrol_volatile *vd;
if(!dev || !value) {
LOGE(LOG_TAG, "%s:%d, dev or info is null", __func__, __LINE__);
return -EINVAL;
}
kctl = audio_ctl_find_id(dev, &value->id);
if(!kctl) {
LOGE(LOG_TAG, "%s:%d, no matched kctl", __func__, __LINE__);
return -ENOENT;
}
vd = &kctl->vd[0];
if ((vd->access & AOS_CTL_ELEM_ACCESS_READ) && kctl->get != NULL) {
//audio_ctl_build_ioff(&value->id, kctl, index_offset);
value->id = kctl->id;
ret = kctl->get(kctl, value);
}
return ret;
}
int audio_ctl_elem_write(ctrl_device_t *dev, struct audio_ctl_elem_value *value)
{
int ret = -1;
struct audio_kcontrol *kctl;
struct audio_kcontrol_volatile *vd;
if(!dev || !value) {
LOGE(LOG_TAG, "%s:%d, dev or value is null", __func__, __LINE__);
return -EINVAL;
}
kctl = audio_ctl_find_id(dev, &value->id);
if(!kctl) {
LOGE(LOG_TAG, "%s:%d, no matched kctl", __func__, __LINE__);
return -ENOENT;
}
vd = &kctl->vd[0];
if ((vd->access & AOS_CTL_ELEM_ACCESS_WRITE) && kctl->put != NULL) {
//audio_ctl_build_ioff(&value->id, kctl, index_offset);
value->id = kctl->id;
ret = kctl->put(kctl, value);
}
return ret;
}
int audio_ctl_tlv_ioctl(ctrl_device_t *dev, struct audio_ctl_tlv *tlv, int op_flag)
{
int ret = -1;
struct audio_kcontrol *kctl;
if(!dev || !tlv) {
LOGE(LOG_TAG, "%s:%d, dev or tlv is null", __func__, __LINE__);
return -EINVAL;
}
kctl = audio_ctl_find_numid(dev, tlv->numid);
if(!kctl) {
LOGE(LOG_TAG, "%s:%d, no matched kctl", __func__, __LINE__);
return -ENOENT;
}
if(!kctl->tlv.c) {
LOGE(LOG_TAG, "%s:%d, kctl->tlv.c is null", __func__, __LINE__);
return -EPERM;
}
ret = kctl->tlv.c(kctl, op_flag, tlv->len, tlv->tlv);
return ret;
}
int get_integer_info(struct audio_kcontrol * kcontrol, struct audio_ctl_elem_info * uinfo)
{
struct audio_mixer_control *mc = (struct audio_mixer_control *)kcontrol->private_value;
int platform_max;
if (!mc->platform_max)
mc->platform_max = mc->max;
platform_max = mc->platform_max;
if (platform_max == 1 && !strstr((const char*)kcontrol->id.name, " Volume"))
uinfo->type = AOS_CTL_ELEM_TYPE_BOOLEAN;
else
uinfo->type = AOS_CTL_ELEM_TYPE_INTEGER;
uinfo->id = kcontrol->id;
uinfo->count = 1;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = platform_max - mc->min;
return 0;
}
| YifuLiu/AliOS-Things | components/a2sa/src/driver/core/control.c | C | apache-2.0 | 13,638 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <ulog/ulog.h>
#include <string.h>
#include "control_dev.h"
#define LOG_TAG "[control_dev]"
ctrl_device_t *audio_ctrl_device_new(int id)
{
ctrl_device_t *dev = NULL;
dev = (ctrl_device_t *)malloc(sizeof(ctrl_device_t));
if(!dev) {
LOGE(LOG_TAG, "%s:%d, malloc dev failed!!!", __func__, __LINE__);
return NULL;
}
memset(dev, 0, sizeof(ctrl_device_t));
dev->id = id;
snprintf(dev->name, sizeof(dev->name), "/dev/controlC%d", id);
dlist_init(&dev->kcontrol_list);
return dev;
}
int audio_ctrl_device_free(ctrl_device_t *dev)
{
if(!dev) {
LOGE(LOG_TAG, "%s:%d, dev is null!!!", __func__, __LINE__);
return -1;
}
dev->parent_data = NULL;
free(dev);
dev = NULL;
return 0;
} | YifuLiu/AliOS-Things | components/a2sa/src/driver/core/control_dev.c | C | apache-2.0 | 840 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <errno.h>
#include <ulog/ulog.h>
#include <string.h>
#include "pcm_dev.h"
#define LOG_TAG "[pcm_dev]"
pcm_device_t * audio_pcm_device_new(int dirType, const char *name, pcm_device_ops_t *ops, void *private_data)
{
pcm_device_t *dev = NULL;
if((dirType < AUDIO_DEVICE_TYPE_PCM_CAPTURE) || (dirType > AUDIO_DEVICE_TYPE_PCM_PLAYBACK)) {
LOGE(LOG_TAG, "%s:%d, invalid dirType %d", __func__, __LINE__, dirType);
return NULL;
}
if(!name) {
LOGE(LOG_TAG, "%s:%d, pcm name is null", __func__, __LINE__);
return NULL;
}
dev = malloc(sizeof(pcm_device_t));
if(!dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return NULL;
}
dev->dirType = dirType;
dev->name = strdup(name);
if(!dev->name) {
LOGE(LOG_TAG, "%s:%d, strdup name failed", __func__, __LINE__);
free(dev);
return NULL;
}
dev->ops = ops;
dev->private_data = private_data;
dlist_init(&dev->list);
return dev;
}
int audio_pcm_device_free(pcm_device_t *dev)
{
if(!dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
dlist_del(&dev->list);
free(dev->name);
free(dev);
dev = NULL;
return 0;
}
| YifuLiu/AliOS-Things | components/a2sa/src/driver/core/pcm_dev.c | C | apache-2.0 | 1,351 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <string.h>
#include <errno.h>
#include <ulog/ulog.h>
#include "audio_rtos.h"
#include "audio_card.h"
#include "pcm_dev.h"
#include "pb_task.h"
#include "cap_task.h"
#define LOG_TAG "[audio_rtos]"
static native_pcm_device_t native_device[2];
static int pcm_open(void *dev)
{
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(pcm_dev->isOpenState) {
//return -EBUSY;
return 0; /* WAR in case app not close pcm stream before open. */
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
pcm_dev->isOpenState = true;
return 0;
}
static int pcm_hw_params(void *dev, audio_hw_params_t *params)
{
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!params) {
LOGE(LOG_TAG, "%s:%d, params is null", __func__, __LINE__);
return -EINVAL;
}
pcm_dev->params.block = params->block;
pcm_dev->params.interleave = params->interleave;
pcm_dev->params.rate = params->rate;
pcm_dev->params.channels = params->channels;
pcm_dev->params.sample_bits = params->sample_bits;
return 0;
}
static int pcm_sw_params(void *dev, audio_sw_params_t *params)
{
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!params) {
LOGE(LOG_TAG, "%s:%d, params is null", __func__, __LINE__);
return -EINVAL;
}
pcm_dev->swParams.hdl = params->hdl;
pcm_dev->swParams.period = params->period;
return 0;
}
static int pcm_hw_prepare(void *dev)
{
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->open) {
LOGE(LOG_TAG, "%s:%d, dev ops open is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->hdl) {
/* if 1st time open this pcm stream */
pcm_dev->hdl = pcm_dev->ops->open(pcm_dev->mode, pcm_dev->params.rate, pcm_dev->params.channels, pcm_dev->params.sample_bits, pcm_dev->swParams.hdl);
if(!pcm_dev->hdl) {
LOGE(LOG_TAG, "%s:%d, pcm_dev open failed", __func__, __LINE__);
return -1;
}
} else {
/* if not 1st time open this stream, it means recovering this stream */
pcm_dev->ops->close(pcm_dev->hdl);
/* if 1st time open this pcm stream */
pcm_dev->hdl = pcm_dev->ops->open(pcm_dev->mode, pcm_dev->params.rate, pcm_dev->params.channels, pcm_dev->params.sample_bits, pcm_dev->swParams.hdl);
if(!pcm_dev->hdl) {
LOGE(LOG_TAG, "%s:%d, pcm_dev open failed", __func__, __LINE__);
return -1;
}
}
return 0;
}
static int pcm_start(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->start) {
LOGE(LOG_TAG, "%s:%d, dev ops start is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm_dev->ops->start(pcm_dev->hdl);
if(pcm_dev->mode == PCM_STREAM_OUT) {
/* start playback thread */
playback_task_start();
} else {
/* start playback thread */
capture_task_start(dev);
}
return ret;
}
static int pcm_readi(void *dev, audio_xferi_t *xbuf)
{
int ret = -1;
unsigned int byte_len = 0, frame_size = 0;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
frame_size = (pcm_dev->params.channels) * (pcm_dev->params.sample_bits) / 8;
byte_len = xbuf->frames * frame_size;
ret = capture_read_data(pcm_dev, xbuf->buf, byte_len, pcm_dev->params.block);
xbuf->result = (ret > 0) ? ret / frame_size : 0;
return 0;
}
static int pcm_writei(void *dev, audio_xferi_t *xbuf)
{
int ret = 0;
int byte_len = 0, frame_size = 0;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->write) {
LOGE(LOG_TAG, "%s:%d, dev ops write is null", __func__, __LINE__);
return -EINVAL;
}
if(!xbuf || !(xbuf->buf)) {
LOGE(LOG_TAG, "%s:%d, invalid xbuf", __func__, __LINE__);
return -EINVAL;
}
frame_size = (pcm_dev->params.channels) * (pcm_dev->params.sample_bits) / 8;
byte_len = (xbuf->frames) * frame_size;
ret = playback_push_data(dev, xbuf->buf, byte_len, pcm_dev->params.block);
xbuf->result = (ret > 0) ? ret / frame_size : 0;
return 0;
}
static int pcm_readn(void *dev, audio_xfern_t *xbuf)
{
int ret = 0;
LOGE(LOG_TAG, "%s:%d, unsupported by now", __func__, __LINE__);
return ret;
}
static int pcm_writen(void *dev, audio_xfern_t *xbuf)
{
int ret = 0;
LOGE(LOG_TAG, "%s:%d, unsupported by now", __func__, __LINE__);
return ret;
}
int pcm_drain(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(pcm_dev->mode == PCM_STREAM_OUT) {
/* stop playback task */
ret = playback_task_drain();
}
LOGE(LOG_TAG, "%s:%d", __func__, __LINE__);
return ret;
}
int pcm_pause(void *dev, int enable)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->pause) {
LOGE(LOG_TAG, "%s:%d, dev ops close is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm_dev->ops->pause(pcm_dev->hdl, enable);
return ret;
}
int pcm_suspend(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->suspend) {
LOGE(LOG_TAG, "%s:%d, dev ops close is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm_dev->ops->suspend(pcm_dev->hdl);
return ret;
}
int pcm_resume(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->resume) {
LOGE(LOG_TAG, "%s:%d, dev ops close is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm_dev->ops->resume(pcm_dev->hdl);
return ret;
}
int pcm_stop(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->stop) {
LOGE(LOG_TAG, "%s:%d, dev ops stop is null", __func__, __LINE__);
return -EINVAL;
}
if(pcm_dev->mode == PCM_STREAM_OUT) {
/* stop playback task */
playback_task_stop();
} else {
/* stop capture task */
capture_task_stop();
}
ret = pcm_dev->ops->stop(pcm_dev->hdl);
LOGE(LOG_TAG, "%s:%d", __func__, __LINE__);
return ret;
}
int pcm_close(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->close) {
LOGE(LOG_TAG, "%s:%d, dev ops close is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm_dev->ops->close(pcm_dev->hdl);
pcm_dev->hdl = NULL;
pcm_dev->isOpenState = false;
return ret;
}
int pcm_recover(void *dev)
{
int ret = -1;
native_pcm_device_t *pcm_dev = (native_pcm_device_t *)dev;
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops) {
LOGE(LOG_TAG, "%s:%d, dev ops is null", __func__, __LINE__);
return -EINVAL;
}
if(!pcm_dev->ops->recover) {
LOGE(LOG_TAG, "%s:%d, dev ops close is null", __func__, __LINE__);
return -EINVAL;
}
ret = pcm_dev->ops->recover(pcm_dev->hdl);
return ret;
}
static pcm_device_ops_t pcm_dev_ops = {
.open = pcm_open,
.hw_params = pcm_hw_params,
.sw_params = pcm_sw_params,
.hw_prepare = pcm_hw_prepare,
.start = pcm_start,
.readi = pcm_readi,
.readn = pcm_readn,
.writei = pcm_writei,
.writen = pcm_writen,
.drain = pcm_drain,
.pause = pcm_pause,
.resume = pcm_resume,
.stop = pcm_stop,
.close = pcm_close,
.recover = pcm_recover,
};
/**
* audio_native_card_register - create an audio card
* @rec_num: recoder number
* @spk_num: speaker number
* @controls: audio_kcontrol_new properties belongs to audio card
* @controls_num: audio_kcontrol_new number
*/
int audio_native_card_register(int rec_num, int spk_num, pcm_stream_ops_t *ops, const struct audio_kcontrol_new *controls, int controls_num)
{
int ret = -1;
audio_card_t *card = NULL;
pcm_device_t *pcm_dev = NULL;
char name[20] = {0};
card = audio_card_new();
if(!card) {
LOGE(LOG_TAG, "%s:%d, new card failed", __func__, __LINE__);
return ret;
}
if(rec_num > 0) {
snprintf(name, sizeof(name), "/dev/pcmC%dD%dc", card->id, card->pcm_str_num);
pcm_dev = audio_pcm_device_new(AUDIO_DEVICE_TYPE_PCM_CAPTURE, name, &pcm_dev_ops, (void*)&native_device[0]);
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, new capture device failed", __func__, __LINE__);
return -ENOMEM;
}
native_device[0].mode = PCM_STREAM_IN;
native_device[0].ops = ops;
native_device[0].parent_data = (void *)card;
ret = audio_card_add_pcm_dev(card, pcm_dev);
if(ret < 0) {
LOGE(LOG_TAG, "%s:%d, add capture device failed", __func__, __LINE__);
return ret;
}
}
if(spk_num > 0) {
snprintf(name, sizeof(name), "/dev/pcmC%dD%dp", card->id, card->pcm_str_num);
pcm_dev = audio_pcm_device_new(AUDIO_DEVICE_TYPE_PCM_PLAYBACK, name, &pcm_dev_ops, (void*)&native_device[1]);
if(!pcm_dev) {
LOGE(LOG_TAG, "%s:%d, new playback device failed", __func__, __LINE__);
return -ENOMEM;
}
native_device[1].mode = PCM_STREAM_OUT;
native_device[1].ops = ops;
native_device[1].parent_data = (void *)card;
ret = audio_card_add_pcm_dev(card, pcm_dev);
if(ret < 0) {
LOGE(LOG_TAG, "%s:%d, add playback device failed", __func__, __LINE__);
return ret;
}
}
card->pcm_str_num++;
if(controls && controls_num > 0) {
audio_add_controls(card->ctrl_dev, controls, controls_num, NULL);
}
return 0;
}
| YifuLiu/AliOS-Things | components/a2sa/src/driver/platform/rtos/audio_rtos.c | C | apache-2.0 | 12,364 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifdef HAAS_AUDIO_DEMO
#include <posix/pthread.h>
#else
#include <pthread.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <aos/kernel.h>
#include <aos/list.h>
#include <errno.h>
#include "ulog/ulog.h"
#include "audio_rtos.h"
#define LOG_TAG "[cap_task]"
#define CAP_HIGH_STACKSIZE 8192
#define CAP_DEFAULT_PRIORITY 33
#define CAP_TIMER_DEFAULT_INTERVAL_MS 20 // default capture thread interval 20ms
#define CAP_DATA_BUFFER_ENTRY_NUM_MAX 50 // default capture data buffer size 1s
typedef struct {
struct dlist_s list;
char *data;
unsigned int size;
unsigned int wOffset;
void *dev;
} cap_data_buf_t;
static native_pcm_device_t *pcm_dev = NULL;
static pthread_cond_t cap_cond;
static pthread_mutex_t cap_mutex;
static pthread_t cap_thread;
static bool bCreateCapThreadFlag = false;
static bool bCapStartFlag = false;
static unsigned int cap_interval_ms = CAP_TIMER_DEFAULT_INTERVAL_MS;
static aos_hdl_t flagMutex;
AOS_DLIST_HEAD(cap_data_list);
static void capture_task_drop()
{
dlist_t *temp = NULL;
cap_data_buf_t *data_buf = NULL;
dlist_for_each_entry_safe(&cap_data_list, temp, data_buf, cap_data_buf_t, list) {
if(data_buf) {
dlist_del(&data_buf->list);
free(data_buf->data);
free(data_buf);
}
}
}
static void cap_thread_loop(void *arg)
{
cap_data_buf_t *databuf = NULL;
unsigned int frame_size, period_bytes;
bool copyStartFlag = false;
while(1) {
aos_mutex_lock(&flagMutex, AOS_WAIT_FOREVER);
copyStartFlag = bCapStartFlag;
aos_mutex_unlock(&flagMutex);
if(true == copyStartFlag) {
if(dlist_entry_number(&cap_data_list) >= CAP_DATA_BUFFER_ENTRY_NUM_MAX) {
LOGE(LOG_TAG, "%s:%d, capure data list full, report buf overflow event to APP!!", __func__, __LINE__);
} else if(pcm_dev && pcm_dev->ops && pcm_dev->ops->read) {
frame_size = pcm_dev->params.channels * pcm_dev->params.sample_bits / 8;
period_bytes = frame_size * cap_interval_ms * pcm_dev->params.rate / 1000;
databuf = malloc(sizeof(cap_data_buf_t));
if(databuf) {
databuf->data = malloc(period_bytes);
if(databuf->data) {
memset(databuf->data, 0, period_bytes);
databuf->size = pcm_dev->ops->read(pcm_dev->hdl, databuf->data, period_bytes);
databuf->wOffset = 0;
databuf->dev = pcm_dev;
dlist_init(&databuf->list);
dlist_add_tail(&databuf->list, &cap_data_list);
}
}
} else {
LOGE(LOG_TAG, "%s:%d, invalid pcm_dev params", __func__, __LINE__);
}
usleep(cap_interval_ms * 1000);
} else {
LOGE(LOG_TAG, "%s:%d, wait for cap_cond", __func__, __LINE__);
capture_task_drop();
pthread_cond_wait(&cap_cond, &cap_mutex);
}
}
return 0;
}
static int create_cap_task(void)
{
if(bCreateCapThreadFlag == true) {
LOGD(LOG_TAG, "%s:%d, capthread is running, skip ...", __func__, __LINE__);
return -1;
}
LOGD(LOG_TAG, "%s:%d, -->>", __func__, __LINE__);
pthread_attr_t attr;
struct sched_param sched;
aos_mutex_new(&flagMutex);
pthread_cond_init(&cap_cond, NULL);
pthread_mutex_init(&cap_mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, CAP_HIGH_STACKSIZE);
sched.sched_priority = CAP_DEFAULT_PRIORITY;
sched.slice = 0;
pthread_attr_setschedparam(&attr, &sched);
pthread_create(&cap_thread, &attr, cap_thread_loop, NULL);
if (cap_thread) {
pthread_setname_np(cap_thread, "capthread");
}
pthread_attr_destroy(&attr);
bCreateCapThreadFlag = true;
return 0;
}
void capture_task_start(void *dev)
{
LOGD(LOG_TAG, "%s:%d", __func__, __LINE__);
if(!dev) {
LOGE(LOG_TAG, "%s:%d, dev is null", __func__, __LINE__);
}
pcm_dev = dev;
aos_mutex_lock(&flagMutex, AOS_WAIT_FOREVER);
bCapStartFlag = true;
aos_mutex_unlock(&flagMutex);
create_cap_task();
pthread_cond_signal(&cap_cond);
}
void capture_task_stop()
{
LOGD(LOG_TAG, "%s:%d", __func__, __LINE__);
aos_mutex_lock(&flagMutex, AOS_WAIT_FOREVER);
bCapStartFlag = false;
aos_mutex_unlock(&flagMutex);
}
int capture_read_data(void *dev, char *buf, unsigned int len, int blockMode)
{
dlist_t *temp = NULL;
cap_data_buf_t *data_buf = NULL;
unsigned int left_bytes = len;
unsigned int read_bytes = 0;
__read_routin__:
dlist_for_each_entry_safe(&cap_data_list, temp, data_buf, cap_data_buf_t, list) {
if(data_buf && (data_buf->dev == dev)) {
if((data_buf->size - data_buf->wOffset) >= left_bytes) {
memcpy(buf + read_bytes, data_buf->data + data_buf->wOffset, left_bytes);
read_bytes += left_bytes;
data_buf->wOffset += left_bytes;
left_bytes = 0;
return read_bytes;
} else {
memcpy(buf + read_bytes, data_buf->data + data_buf->wOffset, data_buf->size - data_buf->wOffset);
read_bytes += data_buf->size - data_buf->wOffset;
data_buf->wOffset = data_buf->size;
left_bytes -= data_buf->size - data_buf->wOffset;
}
if(data_buf->wOffset >= data_buf->size) {
/* free data_buf */
dlist_del(&data_buf->list);
free(data_buf->data);
free(data_buf);
}
}
}
if(1 == blockMode && read_bytes < len) {
usleep(cap_interval_ms * 1000);
goto __read_routin__;
}
return read_bytes;
}
| YifuLiu/AliOS-Things | components/a2sa/src/driver/platform/rtos/cap_task.c | C | apache-2.0 | 6,038 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#ifdef HAAS_AUDIO_DEMO
#include <posix/pthread.h>
#else
#include <pthread.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <aos/kernel.h>
#include <aos/list.h>
#include <errno.h>
#include "ulog/ulog.h"
#include "audio_rtos.h"
#define LOG_TAG "[pb_task]"
#define PB_HIGH_STACKSIZE 8192
#define PB_DEFAULT_PRIORITY 33
#define PB_TIMER_INTERVAL_MS 20 // minimum interval 20ms
#define PB_TIMER_MAX_IDLE_TIME_MS 2000 // max idle time 2s
#define PB_DATA_BUFFER_ENTRY_NUM_MAX 10
typedef struct {
struct dlist_s list;
char *data;
unsigned int size;
unsigned int wOffset;
void *dev;
} pb_data_buf_t;
static pthread_cond_t pb_cond;
static pthread_mutex_t pb_mutex;
static pthread_t pb_thread;
static bool bCreatePbThreadFlag = false;
static bool bPbStartFlag = false;
static aos_hdl_t flagMutex;
AOS_DLIST_HEAD(pb_data_list);
static void pb_thread_loop(void *arg)
{
pb_data_buf_t *data_buf = NULL;
native_pcm_device_t *pcm_dev = NULL;
dlist_t *temp = NULL;
unsigned int frame_size, period_bytes, left_bytes;
unsigned int sleepCntUs;
long long now_ts = 0;
static int totalIdleTime = 0;
bool copyStartFlag = false;
LOGD(LOG_TAG, "%s:%d, entry!! bPbStartFlag %d", __func__, __LINE__, bPbStartFlag);
while(1) {
now_ts = aos_calendar_localtime_get();
aos_mutex_lock(&flagMutex, AOS_WAIT_FOREVER);
copyStartFlag = bPbStartFlag;
aos_mutex_unlock(&flagMutex);
if(true == copyStartFlag) {
sleepCntUs = PB_TIMER_INTERVAL_MS * 1000;
if(dlist_empty(&pb_data_list)) {
totalIdleTime ++;
if(totalIdleTime > PB_TIMER_MAX_IDLE_TIME_MS / PB_TIMER_INTERVAL_MS) {
sleepCntUs = PB_TIMER_INTERVAL_MS * 100 * 1000;
}
LOGE(LOG_TAG, "%s:%d, data list empty, underflow!!", __func__, __LINE__);
} else {
data_buf = dlist_first_entry(&pb_data_list, pb_data_buf_t, list);
if(data_buf && data_buf->data && data_buf->dev) {
pcm_dev = (native_pcm_device_t *)data_buf->dev;
frame_size = pcm_dev->params.channels * pcm_dev->params.sample_bits / 8;
period_bytes = frame_size * PB_TIMER_INTERVAL_MS * pcm_dev->params.rate / 1000;
left_bytes = data_buf->size - data_buf->wOffset;
if(left_bytes > period_bytes) {
pcm_dev->ops->write(pcm_dev->hdl, data_buf->data + data_buf->wOffset, period_bytes);
data_buf->wOffset += period_bytes;
//LOGE(LOG_TAG, "%s:%d, fetch %d bytes from buffer", __func__, __LINE__, period_bytes);
} else {
pcm_dev->ops->write(pcm_dev->hdl, data_buf->data + data_buf->wOffset, left_bytes);
data_buf->wOffset += left_bytes;
sleepCntUs = left_bytes * PB_TIMER_INTERVAL_MS * 1000 / period_bytes;
//LOGE(LOG_TAG, "%s:%d, fetch %d bytes from buffer", __func__, __LINE__, left_bytes);
/* free data_buf */
dlist_del(&data_buf->list);
free(data_buf->data);
free(data_buf);
}
}
}
now_ts = (aos_calendar_localtime_get() - now_ts) * 1000;
if(sleepCntUs > now_ts) {
usleep(sleepCntUs - now_ts);
}
} else {
LOGD(LOG_TAG, "%s:%d, wait for pb_cond", __func__, __LINE__);
dlist_for_each_entry_safe(&pb_data_list, temp, data_buf, pb_data_buf_t, list) {
if(data_buf) {
dlist_del(&data_buf->list);
free(data_buf->data);
free(data_buf);
}
}
pthread_cond_wait(&pb_cond, &pb_mutex);
}
}
return 0;
}
static int create_pb_task(void)
{
if(bCreatePbThreadFlag == true) {
LOGD(LOG_TAG, "%s:%d, pbthread is running, skip ...", __func__, __LINE__);
return -1;
}
LOGD(LOG_TAG, "%s:%d, -->>", __func__, __LINE__);
pthread_attr_t attr;
struct sched_param sched;
aos_mutex_new(&flagMutex);
pthread_cond_init(&pb_cond, NULL);
pthread_mutex_init(&pb_mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, PB_HIGH_STACKSIZE);
sched.sched_priority = PB_DEFAULT_PRIORITY;
sched.slice = 0;
pthread_attr_setschedparam(&attr, &sched);
pthread_create(&pb_thread, &attr, pb_thread_loop, NULL);
if (pb_thread) {
pthread_setname_np(pb_thread, "pbthread");
}
pthread_attr_destroy(&attr);
bCreatePbThreadFlag = true;
return 0;
}
void playback_task_start()
{
LOGE(LOG_TAG, "%s:%d", __func__, __LINE__);
aos_mutex_lock(&flagMutex, AOS_WAIT_FOREVER);
bPbStartFlag = true;
aos_mutex_unlock(&flagMutex);
create_pb_task();
pthread_cond_signal(&pb_cond);
}
void playback_task_stop()
{
LOGE(LOG_TAG, "%s:%d", __func__, __LINE__);
aos_mutex_lock(&flagMutex, AOS_WAIT_FOREVER);
bPbStartFlag = false;
aos_mutex_unlock(&flagMutex);
}
int playback_task_drain()
{
while(!dlist_empty(&pb_data_list)) {
aos_msleep(PB_TIMER_INTERVAL_MS);
}
return 0;
}
int playback_push_data(void *dev, const char *buf, unsigned int len, int blockMode)
{
if(1 == blockMode) {
while(dlist_entry_number(&pb_data_list) >= PB_DATA_BUFFER_ENTRY_NUM_MAX) {
usleep(PB_TIMER_INTERVAL_MS * 1000);
}
}
if(dlist_entry_number(&pb_data_list) >= PB_DATA_BUFFER_ENTRY_NUM_MAX) {
return 0;
}
pb_data_buf_t *databuf = malloc(sizeof(pb_data_buf_t));
if(!databuf) {
LOGE(LOG_TAG, "%s:%d, malloc pb_data_buf_t failed", __func__, __LINE__);
return -1;
}
databuf->data = malloc(len);
if(!databuf->data) {
LOGE(LOG_TAG, "%s:%d, malloc %d bytes failed", __func__, __LINE__, len);
return -1;
}
memset(databuf->data, 0, len);
databuf->size = len;
memcpy(databuf->data, buf, len);
databuf->wOffset = 0;
databuf->dev = dev;
dlist_init(&databuf->list);
dlist_add_tail(&databuf->list, &pb_data_list);
//LOGE(LOG_TAG, "%s:%d: push %d bytes to buffer", __func__, __LINE__, len);
return len;
} | YifuLiu/AliOS-Things | components/a2sa/src/driver/platform/rtos/pb_task.c | C | apache-2.0 | 6,567 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include <ulog/ulog.h>
#include <string.h>
#include <aos/list.h>
#include "audio_rtos.h"
#include "control.h"
#include <drv/codec.h>
#include <aos/aos.h>
#define LOG_TAG "[template]"
typedef struct {
csi_codec_output_t hdl;
int vol;
int mute;
} mixer_playback_t;
static mixer_playback_t mixer;
static const int playback_stream_hdl = 0;
static const int capture_stream_hdl = 1;
static csi_codec_t codec_a;
static csi_dma_ch_t dma_ch_output_handle;
static int codec_hw_vol_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol);
static int codec_hw_vol_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol);
static int codec_hw_mute_state_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol);
static int codec_hw_mute_state_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol);
static const struct audio_kcontrol_new master_codec_controls[] = {
SOC_SINGLE_EXT("Master Volume TX", /* master volume attribute name: defined in sound_mixer.h */
0,
0, /* codec volume minimum value */
63, /* codec volume maxmum value */
0,
codec_hw_vol_get, /* get codec volume api */
codec_hw_vol_put), /* set codec volume api */
SOC_SINGLE_EXT("Master Mute State", /* master mute attribute name: defined in sound_mixer.h */
0,
0, /* codec mute state minimum value */
1, /* codec mute state maxmum value */
0,
codec_hw_mute_state_get, /* get codec mute state */
codec_hw_mute_state_put), /* put codec mute state */
};
static int codec_hw_mute_state_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol)
{
int mute = mixer.mute;
if(!kcontrol || !ucontrol) {
LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__);
return -1;
}
// TBD: get codec mute state, e.g. mute = ac97_get_mute();
LOGD(LOG_TAG, "%s:%d: get mute state %d \r\n", __func__, __LINE__, mute);
ucontrol->value.integer.value[0] = mute;
return 0;
}
static int codec_hw_mute_state_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol)
{
int mute = 0;
if(!kcontrol || !ucontrol) {
LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__);
return -1;
}
mute = ucontrol->value.integer.value[0];
LOGD(LOG_TAG, "%s:%d: set mute state %d \r\n", __func__, __LINE__, mute);
if (mixer.hdl.callback != NULL && mute != mixer.mute) {
csi_codec_output_t *p = &mixer.hdl;
csi_codec_output_mute(p, mute);
}
mixer.mute = mute;
// TBD: set codec mute state, e.g. ac97_set_mute(mute);
return 0;
}
static int codec_hw_vol_get(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol)
{
int volume = mixer.vol;
if(!kcontrol || !ucontrol) {
LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__);
return -1;
}
// TBD: get codec volume, e.g. volume = ac97_get_vol();
LOGD(LOG_TAG, "%s:%d: get volume %d \r\n", __func__, __LINE__, volume);
ucontrol->value.integer.value[0] = volume;
return 0;
}
static int codec_hw_vol_put(struct audio_kcontrol *kcontrol, struct audio_ctl_elem_value *ucontrol)
{
int volume = 0;
if(!kcontrol || !ucontrol) {
LOGE(LOG_TAG, "%s:%d: invalid params. \r\n", __func__, __LINE__);
return -1;
}
volume = ucontrol->value.integer.value[0];
LOGD(LOG_TAG, "%s:%d: set volume %d \r\n", __func__, __LINE__, volume);
// TBD: set codec volume, e.g. ac97_set_vol(volume);
mixer.vol = volume;
if (mixer.hdl.callback != NULL) {
csi_codec_output_t *p = &mixer.hdl;
if (mixer.mute) {
csi_codec_output_mute(p, 0);
mixer.mute = 0;
}
csi_codec_output_analog_gain(p, volume < -31 ? -31 : volume);
csi_codec_output_mix_gain(p, volume);
}
return 0;
}
typedef struct {
int mode;
csi_codec_output_t *hdl;
int rate;
int channels;
pcm_stream_format_t format;
aos_hdl_t *event_hdl;
int state;
} playback_t;
static void codec_event_cb(csi_codec_input_t *codec, csi_codec_event_t event, void *arg)
{
// playback_t *playback = (playback_t *)arg;
if (event == CODEC_EVENT_PERIOD_WRITE_COMPLETE) {
// pcm->event.cb(pcm, PCM_EVT_WRITE, pcm->event.priv);
} else if (event == CODEC_EVENT_PERIOD_READ_COMPLETE) {
// pcm->event.cb(pcm, PCM_EVT_READ, pcm->event.priv);
} else if (event == CODEC_EVENT_READ_BUFFER_FULL) {
// pcm->event.cb(pcm, PCM_EVT_XRUN, pcm->event.priv);
} else {
// pcm->event.cb(pcm, PCM_EVT_XRUN, pcm->event.priv);
}
}
#define OUTPUT_BUF_SIZE 11520
#define OUTPUT_PERIOD_SIZE 1280
uint8_t output_buf[OUTPUT_BUF_SIZE];
static pcm_stream_handler_t playback_open(int mode, int sampleRate, int channels, int format, aos_hdl_t *event_hdl)
{
#define PLAYBACK_MS (100)
playback_t *playback = aos_zalloc(sizeof(playback_t));
csi_codec_output_t *codec = aos_zalloc(sizeof(csi_codec_output_t));
ringbuffer_t *ring_buf = aos_zalloc(sizeof(ringbuffer_t));
int format_byte = 16/8;
// int format_byte = pcm_formate_to_bytes(format);
int send_size = PLAYBACK_MS * channels * format_byte;
uint8_t *send = aos_malloc(send_size);
if (playback == NULL || codec == NULL || send == NULL || ring_buf == NULL) {
goto playback_err;
}
playback->hdl = codec;
playback->mode = mode;
playback->rate = sampleRate;
playback->channels = channels;
playback->format = format;
playback->event_hdl = event_hdl;
codec->ring_buf = ring_buf;
csi_codec_output_open(&codec_a, codec, 0);
csi_codec_output_attach_callback(codec, codec_event_cb, playback);
csi_codec_output_config_t output_config;
output_config.bit_width = 16;
output_config.sample_rate = sampleRate;
output_config.buffer = output_buf;
output_config.buffer_size = OUTPUT_BUF_SIZE;
output_config.period = OUTPUT_PERIOD_SIZE;
output_config.mode = CODEC_OUTPUT_SINGLE_ENDED;
output_config.sound_channel_num = channels;
int ret = csi_codec_output_config(codec, &output_config);
if (ret != 0) {
goto playback_err;
}
csi_codec_output_analog_gain(codec, 0xaf);
csi_codec_output_buffer_reset(codec);
csi_codec_output_link_dma(codec, &dma_ch_output_handle);
return (pcm_stream_handler_t)playback;
playback_err:
if (playback) {
aos_free(playback);
}
if (codec) {
aos_free(codec);
}
if (ring_buf) {
aos_free(ring_buf);
}
if (send) {
aos_free(send);
}
return NULL;
}
static pcm_stream_handler_t codec_pcm_stream_open(int mode, int sampleRate, int channels, int format, aos_hdl_t *event_hdl)
{
pcm_stream_handler_t hdl = NULL;
if(mode == PCM_STREAM_IN) {
hdl = (pcm_stream_handler_t)&capture_stream_hdl;
// TBD: initializa capture codec
} else if (mode == PCM_STREAM_OUT) {
hdl = (pcm_stream_handler_t)&playback_stream_hdl;
// TBD: initializa playback codec
hdl = playback_open(mode, sampleRate, channels, format, event_hdl);
}
return hdl;
}
static int playback_start(void *hdl)
{
playback_t *playback = (playback_t *)hdl;
csi_codec_output_t *codec = playback->hdl;
csi_codec_output_start(codec);
if (mixer.mute){
// csi_codec_output_mute(codec, 1);
} else {
// csi_codec_output_mute(codec, 0);
// csi_codec_output_analog_gain(codec, mixer.vol);
}
return 0;
}
static int codec_pcm_stream_start(pcm_stream_handler_t hdl)
{
int ret = 0;
int *mode = (int *)hdl;
if(*mode == PCM_STREAM_IN) {
// TBD: start capture stream
} else if (*mode == PCM_STREAM_OUT) {
playback_start(hdl);
}
return ret;
}
static int codec_pcm_stream_write(pcm_stream_handler_t hdl, void *buf, unsigned int len)
{
playback_t *playback = (playback_t *)hdl;
// LOGE("drv", "write enter(%lld)\r\n", aos_now_ms());
int ret = csi_codec_output_write_async(playback->hdl, (uint8_t *)buf, len);
// int ret = csi_codec_output_write(playback->hdl, (uint8_t *)buf, len);
// LOGE("drv", "write(%d)(%d)\r\n", len, ret);
return ret;
}
static int codec_pcm_stream_read(pcm_stream_handler_t hdl, void *buf, unsigned int len)
{
int ret = 0;
if(hdl == &playback_stream_hdl) {
LOGE(LOG_TAG, "%s:%d, read operation not allowed on playback stream.", __func__, __LINE__);
} else if (hdl == &capture_stream_hdl) {
// TBD: read capture stream
}
return ret;
}
static int playback_pause(void *hdl, int enable)
{
playback_t *playback = (playback_t *)hdl;
if (enable) {
// csi_codec_output_pause(playback->hdl);
} else {
// csi_codec_output_resume(playback->hdl);
}
return 0;
}
static int codec_pcm_stream_pause(pcm_stream_handler_t hdl, int enable)
{
int ret = 0;
int *mode = (int *)hdl;
if(*mode == PCM_STREAM_IN) {
// TBD: start capture stream
} else if (*mode == PCM_STREAM_OUT) {
playback_pause(hdl, enable);
}
return ret;
}
static int codec_pcm_stream_suspend(pcm_stream_handler_t hdl)
{
int ret = 0;
if(hdl == &playback_stream_hdl) {
// TBD: put playback stream into lowpower/suspend mode
} else if (hdl == &capture_stream_hdl) {
// TBD: put capture stream into lowpower/suspend mode
}
return ret;
}
static int codec_pcm_stream_resume(pcm_stream_handler_t hdl)
{
int ret = 0;
if(hdl == &playback_stream_hdl) {
// TBD: put playback stream into active mode
} else if (hdl == &capture_stream_hdl) {
// TBD: put playback stream into active mode
}
return ret;
}
static int codec_pcm_stream_stop(pcm_stream_handler_t hdl)
{
int ret = 0;
int *mode = (int *)hdl;
if(*mode == PCM_STREAM_IN) {
// TBD: start capture stream
} else if (*mode == PCM_STREAM_OUT) {
playback_t *playback = (playback_t *)hdl;
csi_codec_output_stop(playback->hdl);
}
return ret;
}
static int codec_pcm_stream_close(pcm_stream_handler_t hdl)
{
int ret = 0;
int *mode = (int *)hdl;
if(*mode == PCM_STREAM_IN) {
// TBD: start capture stream
} else if (*mode == PCM_STREAM_OUT) {
playback_t *playback = (playback_t *)hdl;
csi_codec_output_close(playback->hdl);
}
return ret;
}
static int codec_pcm_stream_recover(pcm_stream_handler_t hdl)
{
int ret = 0;
if(hdl == &playback_stream_hdl) {
// TBD: recover playback stream
} else if (hdl == &capture_stream_hdl) {
// TBD: recover capture stream
}
return ret;
}
pcm_stream_ops_t codec_pcm_ops = {
.open = codec_pcm_stream_open,
.start = codec_pcm_stream_start,
.read = codec_pcm_stream_read,
.write = codec_pcm_stream_write,
.pause = codec_pcm_stream_pause,
.stop = codec_pcm_stream_stop,
.close = codec_pcm_stream_close,
.recover = codec_pcm_stream_recover,
.suspend = codec_pcm_stream_suspend,
.resume = codec_pcm_stream_resume,
};
/* Application shall call this API to install codec driver instance. */
int audio_install_codec_driver()
{
int pb_stream_num = 1;
int cap_stream_num = 1;
csi_codec_init(&codec_a, 0);
LOGD(LOG_TAG, "%s:%d, install RTOS codec driver %d Capture %d Playback", __func__, __LINE__, cap_stream_num, pb_stream_num);
return audio_native_card_register(cap_stream_num, pb_stream_num, &codec_pcm_ops, master_codec_controls, sizeof(master_codec_controls)/sizeof(master_codec_controls[0]));
}
//FINSH_FUNCTION_EXPORT_CMD(audio_install_codec_driver, insmod_audio_drv, RTOS Codec Driver Test) | YifuLiu/AliOS-Things | components/a2sa/src/driver/platform/rtos/template.c | C | apache-2.0 | 11,985 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include "sound_mixer.h"
#include "ulog/ulog.h"
#define LOG_TAG "[sound_mixer]"
#define MIXER_RETURN_ERR -1
#define MIXER_RETURN_SUCCESS 0
#define AOS_MASTER_VOLUME_TX_STRING "Master Volume TX"
#define AOS_MASTER_MUTE_STATE_STRING "Master Mute State"
static int aos_mixer_common_set_int_value(char *name, int value)
{
int card = 0;
aos_mixer_t *mixer = NULL;
if(!name) {
return MIXER_RETURN_ERR;
}
for(card = 0; card < AOS_SNDCARD_NUM_MAX; card++) {
if(MIXER_RETURN_SUCCESS == aos_mixer_open(&mixer, card)) {
aos_mixer_print_info(mixer);
if(MIXER_RETURN_SUCCESS == aos_mixer_set_int_value(mixer, name, value)) {
aos_mixer_close(mixer);
mixer = NULL;
return MIXER_RETURN_SUCCESS;
}
}
aos_mixer_close(mixer);
mixer = NULL;
}
return MIXER_RETURN_ERR;
}
int aos_mixer_common_get_int_value(char *name, int *value)
{
int card = 0;
aos_mixer_t *mixer = NULL;
if(!name) {
return MIXER_RETURN_ERR;
}
for(card = 0; card < AOS_SNDCARD_NUM_MAX; card++) {
if(MIXER_RETURN_SUCCESS == aos_mixer_open(&mixer, card)) {
aos_mixer_print_info(mixer);
if(MIXER_RETURN_SUCCESS == aos_mixer_get_int_value(mixer, name, value)) {
aos_mixer_close(mixer);
mixer = NULL;
return MIXER_RETURN_SUCCESS;
}
}
aos_mixer_close(mixer);
mixer = NULL;
}
return MIXER_RETURN_ERR;
}
int aos_mixer_open(aos_mixer_t **mixer, int card)
{
struct audio_ctl_elem_list elist;
struct audio_ctl_elem_id *eid = NULL;
struct audio_ctl_elem_info *ei = NULL;
int fd;
unsigned int n;
char fn[256];
/* 1. open fd */
snprintf(fn, sizeof(fn), "/dev/controlC%u", card);
fd = open(fn, O_RDWR);
if (fd < 0) {
LOGE(LOG_TAG, "%s:%d, open %s failed", __func__, __LINE__, fn);
return MIXER_RETURN_ERR;
}
LOGD(LOG_TAG, "%s:%d, open %s successfully", __func__, __LINE__, fn);
/* 2. new aos_mixer_t object */
*mixer = (aos_mixer_t *)calloc(1, sizeof(aos_mixer_t));
memset(*mixer, 0, sizeof(aos_mixer_t));
(*mixer)->fd = fd;
(*mixer)->name = strdup(fn);
(*mixer)->card = card;
/* 3. get elem_list count number */
memset(&elist, 0, sizeof(elist));
if (ioctl(fd, AUDIO_CTL_IOCTL_ELEM_LIST, &elist) < 0) {
return MIXER_RETURN_ERR;
}
(*mixer)->count = elist.count;
elist.space = elist.count;
/* 4. get card info */
if(ioctl(fd, AUDIO_CTL_IOCTL_CARD_INFO, &((*mixer)->card_info)) < 0) {
return MIXER_RETURN_ERR;
}
/* 5. get audio_ctl_elem_list */
eid = calloc(elist.count, sizeof(struct audio_ctl_elem_id));
if(!eid) {
return MIXER_RETURN_ERR;
}
elist.pids = eid;
if (ioctl(fd, AUDIO_CTL_IOCTL_ELEM_LIST, &elist) < 0) {
return MIXER_RETURN_ERR;
}
/* 6. get audio_ctl_elem_info */
(*mixer)->elem_info = calloc(elist.count, sizeof(struct audio_ctl_elem_info));
if(!(*mixer)->elem_info) {
return MIXER_RETURN_ERR;
}
for (n = 0; n < (*mixer)->count; n++) {
ei = (*mixer)->elem_info + n;
ei->id.id = eid[n].id;
if (ioctl(fd, AUDIO_CTL_IOCTL_ELEM_INFO, ei) < 0) {
LOGE(LOG_TAG, "%s:%d, ioctl AUDIO_CTL_IOCTL_ELEM_INFO failed", __func__, __LINE__);
}
}
if(eid) {
free(eid);
}
return MIXER_RETURN_SUCCESS;
}
int aos_mixer_print_info(aos_mixer_t *mixer)
{
const char *type;
unsigned int info_cnt;
unsigned int i;
struct audio_ctl_elem_info * elem_info = NULL;
if(!mixer) {
return MIXER_RETURN_ERR;
}
info_cnt = mixer->count;
LOGD(LOG_TAG, "%s:%d, element_info count %d", __func__, __LINE__, info_cnt);
for (i = 0; i < info_cnt; i++) {
elem_info = mixer->elem_info + i;
switch (elem_info->type) {
case AOS_CTL_ELEM_TYPE_BOOLEAN:
type = "BOOL";
break;
case AOS_CTL_ELEM_TYPE_INTEGER:
type = "INT";
break;
case AOS_CTL_ELEM_TYPE_ENUMERATED:
type = "ENUM";
break;
case AOS_CTL_ELEM_TYPE_BYTES:
type = "BYTE";
break;
case AOS_CTL_ELEM_TYPE_IEC958:
type = "IEC958";
break;
case AOS_CTL_ELEM_TYPE_INTEGER64:
type = "INT64";
break;
default:
type = "Unknown";
break;
}
LOGD(LOG_TAG, "%s:%d, element_info[%d].id.id = %d", __func__, __LINE__, i, elem_info->id.id);
LOGD(LOG_TAG, "%s:%d, element_info[%d].id.name = %s", __func__, __LINE__, i, elem_info->id.name);
LOGD(LOG_TAG, "%s:%d, element_info[%d].count = %d", __func__, __LINE__, i, elem_info->count);
LOGD(LOG_TAG, "%s:%d, element_info[%d].type = %d (%s)", __func__, __LINE__, i, elem_info->type, type);
}
return MIXER_RETURN_SUCCESS;
}
int aos_mixer_set_int_value(aos_mixer_t *mixer, char *name, int value)
{
int i = 0;
struct audio_ctl_elem_info * elem_info = NULL;
struct audio_ctl_elem_value ev;
if(!mixer || !name) {
return MIXER_RETURN_ERR;
}
for(i = 0; i < mixer->count; i++) {
elem_info = mixer->elem_info + i;
if(!strcmp(elem_info->id.name, name)) {
break;
}
}
if(i >= mixer->count) {
return MIXER_RETURN_ERR;
}
if(AOS_CTL_ELEM_TYPE_INTEGER != elem_info->type) {
return MIXER_RETURN_ERR;
}
ev.id.id = elem_info->id.id;
ev.value.integer.value[0] = value;
if(ioctl(mixer->fd, AUDIO_CTL_IOCTL_ELEM_WRITE, &ev) < 0) {
return MIXER_RETURN_ERR;
}
LOGD(LOG_TAG, "%s:%d, set [%s, %d] successfully", __func__, __LINE__, name, value);
return MIXER_RETURN_SUCCESS;
}
int aos_mixer_get_int_value(aos_mixer_t *mixer, char *name, int *value)
{
int i = 0;
struct audio_ctl_elem_info * elem_info = NULL;
struct audio_ctl_elem_value ev;
if(!mixer || !name) {
return MIXER_RETURN_ERR;
}
for(i = 0; i < mixer->count; i++) {
elem_info = mixer->elem_info + i;
if(!strcmp(elem_info->id.name, name)) {
break;
}
}
if(i >= mixer->count) {
return MIXER_RETURN_ERR;
}
if(AOS_CTL_ELEM_TYPE_INTEGER != elem_info->type) {
return MIXER_RETURN_ERR;
}
ev.id.id = elem_info->id.id;
if(ioctl(mixer->fd, AUDIO_CTL_IOCTL_ELEM_READ, &ev) < 0) {
return MIXER_RETURN_ERR;
}
*value = ev.value.integer.value[0];
LOGD(LOG_TAG, "%s:%d, get [%s, %d] successfully", __func__, __LINE__, name, *value);
return MIXER_RETURN_SUCCESS;
}
int aos_mixer_close(aos_mixer_t *mixer)
{
if(!mixer) {
LOGE(LOG_TAG, "%s:%d, invalid mixer", __func__, __LINE__);
return MIXER_RETURN_ERR;
}
if(mixer->fd >= 0) {
close(mixer->fd);
mixer->fd = -1;
}
if(mixer->name) {
free(mixer->name);
mixer->name = NULL;
}
if(mixer->elem_info) {
free(mixer->elem_info);
mixer->elem_info = NULL;
}
free(mixer);
mixer = NULL;
LOGD(LOG_TAG, "%s:%d, close mixer successfully", __func__, __LINE__);
return MIXER_RETURN_SUCCESS;
}
int aos_set_master_volume(int volume)
{
return aos_mixer_common_set_int_value(AOS_MASTER_VOLUME_TX_STRING, volume);
}
int aos_get_master_volume(int *volume)
{
return aos_mixer_common_get_int_value(AOS_MASTER_VOLUME_TX_STRING, volume);
}
int aos_set_mute_state(int mute)
{
return aos_mixer_common_set_int_value(AOS_MASTER_MUTE_STATE_STRING, mute);
}
int aos_get_mute_state(int *mute)
{
return aos_mixer_common_get_int_value(AOS_MASTER_MUTE_STATE_STRING, mute);
}
void aos_mixer_test(char *pbuffer, int outlen, int argc, char **argv)
{
int volume = -1;
if (argc < 1) {
LOGE(LOG_TAG, "%s:%d: Usage: %s", __func__, __LINE__, argv[0]);
return;
}
aos_set_master_volume(55);
aos_get_master_volume(&volume);
aos_set_mute_state(1);
} | YifuLiu/AliOS-Things | components/a2sa/src/framework/sound_mixer.c | C | apache-2.0 | 8,279 |
/*
* Copyright (C) 2015-2020 Alibaba Group Holding Limited
*/
#include "sound_pcm.h"
#include "ulog/ulog.h"
#define LOG_TAG "[sound_pcm]"
#define PCM_LOCK(pcm) aos_mutex_lock(&pcm->mutex, AOS_WAIT_FOREVER)
#define PCM_UNLOCK(pcm) aos_mutex_unlock(&pcm->mutex)
#define PCM_RETURN_ERR -1
#define PCM_RETURN_SUCCESS 0
int aos_device_name_hint(int card, void *hints)
{
int i = 0, j = 0, fd = -1;
char fn[256];
hint_list_t *node = NULL;
if(card == -1) {
for(i = 0; i < AOS_SNDCARD_NUM_MAX; i++) {
for(j = 0; j < AOS_SNDCARD_DEVICE_NUM_MAX; j++) {
memset(fn, 0, sizeof(fn));
snprintf(fn, sizeof(fn), "/dev/pcmC%uD%u%c", i, j, 'p');
fd = open(fn, O_RDWR|O_NONBLOCK);
if (fd > 0) {
node = (hint_list_t *)calloc(1, sizeof(hint_list_t));
if(!node) {
return -ENOMEM;
}
hints = (void *)node;
node->card = i;
node->device = j;
strncpy(node->name, fn, sizeof(node->name) - 1);
close(fd);
LOGD(LOG_TAG, "%s:%d, found sound card %d device %d %s", __func__, __LINE__, i, j, node->name);
return PCM_RETURN_SUCCESS;
}
}
}
} else {
for(j = 0; j < AOS_SNDCARD_DEVICE_NUM_MAX; j++) {
memset(fn, 0, sizeof(fn));
snprintf(fn, sizeof(fn), "/dev/pcmC%uD%u%c", card, j, 'p');
fd = open(fn, O_RDWR|O_NONBLOCK);
if (fd > 0) {
node = (hint_list_t *)calloc(1, sizeof(hint_list_t));
if(!node) {
return -ENOMEM;
}
hints = (void *)node;
node->card = card;
node->device = j;
strncpy(node->name, fn, sizeof(node->name) - 1);
close(fd);
LOGD(LOG_TAG, "%s:%d, found sound card %d device %d %s", __func__, __LINE__, card, j, node->name);
return PCM_RETURN_SUCCESS;
}
}
}
LOGE(LOG_TAG, "%s:%d, found no sound device ", __func__, __LINE__);
return PCM_RETURN_ERR;
}
int aos_pcm_open(aos_pcm_t **pcm, const char *name, aos_pcm_stream_t stream, int mode)
{
int card = 0, device = 0, fd = -1;
char fn[256];
if(!name) {
LOGE(LOG_TAG, "%s:%d, param name is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
*pcm = (aos_pcm_t *)calloc(1, sizeof(aos_pcm_t));
if(NULL == *pcm) {
LOGE(LOG_TAG, "%s:%d, calloc aos_pcm_t failed", __func__, __LINE__);
return -ENOMEM;
}
memset(*pcm, 0, sizeof(aos_pcm_t));
if(!strcmp(name, "default")) {
for(card = 0; card < AOS_SNDCARD_NUM_MAX; card++) {
for(device = 0; device < AOS_SNDCARD_DEVICE_NUM_MAX; device++) {
memset(fn, 0, sizeof(fn));
snprintf(fn, sizeof(fn), "/dev/pcmC%uD%u%c", card, device, (stream == AOS_PCM_STREAM_PLAYBACK) ? 'p' : 'c');
fd = open(fn, O_RDWR|O_NONBLOCK);
if (fd > 0) {
(*pcm)->fd = fd;
(*pcm)->card = card;
(*pcm)->device = device;
(*pcm)->name = strdup(fn);
(*pcm)->stream = stream;
(*pcm)->mode = mode;
(*pcm)->state = AOS_PCM_STATE_OPEN;
aos_mutex_new(&((*pcm)->mutex));
aos_event_new(&((*pcm)->evt), 0);
LOGD(LOG_TAG, "%s:%d, open card %d device %d successfully", __func__, __LINE__, card, device);
return PCM_RETURN_SUCCESS;
}
}
}
} else {
for(card = 0; card < AOS_SNDCARD_NUM_MAX; card++) {
for(device = 0; device < AOS_SNDCARD_DEVICE_NUM_MAX; device++) {
memset(fn, 0, sizeof(fn));
snprintf(fn, sizeof(fn), "/dev/pcmC%uD%u%c", card, device, (stream == AOS_PCM_STREAM_PLAYBACK) ? 'p' : 'c');
if(!strcmp(name, fn)) {
fd = open(fn, O_RDWR|O_NONBLOCK);
if (fd > 0) {
(*pcm)->fd = fd;
(*pcm)->card = card;
(*pcm)->device = device;
(*pcm)->name = strdup(fn);
(*pcm)->stream = stream;
(*pcm)->mode = mode;
(*pcm)->state = AOS_PCM_STATE_OPEN;
aos_mutex_new(&((*pcm)->mutex));
aos_event_new(&((*pcm)->evt), 0);
LOGD(LOG_TAG, "%s:%d, open card %d device %d successfully", __func__, __LINE__, card, device);
return PCM_RETURN_SUCCESS;
}
}
}
}
}
LOGE(LOG_TAG, "%s:%d, open %s device failed", __func__, __LINE__, (stream == AOS_PCM_STREAM_PLAYBACK) ? "playback" : "capture");
free(*pcm);
*pcm = NULL;
return PCM_RETURN_ERR;
}
int aos_pcm_prepare(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_PREPARE)) {
LOGE(LOG_TAG, "%s:%d, ioctl prepare failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
} else {
pcm->state = AOS_PCM_STATE_PREPARED;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_start(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_START)) {
LOGE(LOG_TAG, "%s:%d, ioctl start failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
} else {
pcm->state = AOS_PCM_STATE_RUNNING;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_wait(aos_pcm_t *pcm, int timeout)
{
int ret = PCM_RETURN_SUCCESS;
unsigned int actl_flags = 0;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
aos_event_get(&pcm->evt, AOS_PCM_EVT_READ | AOS_PCM_EVT_XRUN, AOS_EVENT_OR_CLEAR, &actl_flags, timeout);
PCM_UNLOCK(pcm);
if (actl_flags & AOS_EVENT_OR_CLEAR) {
LOGE(LOG_TAG,"PCM_EVT_XRUN");
return -EPIPE;
}
return ret; // TBD 2x : ret value + evt to driver
}
int aos_pcm_stop(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_DROP)) {
LOGE(LOG_TAG, "%s:%d, ioctl drop failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
} else {
pcm->state = AOS_PCM_STATE_PAUSED;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_drain(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_DRAIN)) {
LOGE(LOG_TAG, "%s:%d, ioctl drain failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_pause(aos_pcm_t *pcm, int enable)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_PAUSE, enable)) {
LOGE(LOG_TAG, "%s:%d, ioctl pause failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_close(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(close(pcm->fd)) {
LOGE(LOG_TAG, "%s:%d, close pcm failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
if(pcm->name) {
free(pcm->name);
}
if(pcm->open_func) {
free(pcm->open_func);
}
if(pcm->private_data) {
free(pcm->private_data);
}
if(pcm->hw_params) {
free(pcm->hw_params);
}
if(pcm->sw_params) {
free(pcm->sw_params);
}
PCM_UNLOCK(pcm);
free(pcm);
return ret;
}
int aos_pcm_recover(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_RECOVER)) {
LOGE(LOG_TAG, "%s:%d, ioctl recover failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_suspend(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_SUSPEND)) {
LOGE(LOG_TAG, "%s:%d, ioctl suspend failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_resume(aos_pcm_t *pcm)
{
int ret = PCM_RETURN_SUCCESS;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_RESUME)) {
LOGE(LOG_TAG, "%s:%d, ioctl resume failed", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_hw_params_alloca(aos_pcm_hw_params_t **p)
{
*p = (aos_pcm_hw_params_t *)calloc(1, sizeof(aos_pcm_hw_params_t));
if(NULL == *p) {
LOGE(LOG_TAG, "%s:%d, calloc aos_pcm_hw_params_t failed", __func__, __LINE__);
return -ENOMEM;
}
return PCM_RETURN_SUCCESS;
}
int aos_pcm_hw_params_any(aos_pcm_hw_params_t *params)
{
if(!params) {
return PCM_RETURN_ERR;
}
params->access = AOS_PCM_ACCESS_RW_INTERLEAVED;
params->format = AOSRV_PCM_FORMAT_S16_LE;
params->channels = 2;
params->rate = 16000;
params->sample_bits = (params->format * 8);
params->frame_bits = (params->format * params->channels * 8);
return PCM_RETURN_SUCCESS;
}
int aos_pcm_hw_params(aos_pcm_t *pcm, aos_pcm_hw_params_t *p)
{
int ret = PCM_RETURN_SUCCESS;
audio_hw_params_t params;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(p && pcm->hw_params) {
memcpy(pcm->hw_params, p, sizeof(aos_pcm_hw_params_t));
}
PCM_LOCK(pcm);
params.block = (pcm->mode & AOS_PCM_NONBLOCK) ? 0 : 1;
params.interleave = (p->access == AOS_PCM_ACCESS_RW_NONINTERLEAVED) ? 0 : 1;
params.channels = p->channels;
params.rate = p->rate;
params.sample_bits = p->format * 8;
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_HW_PARAMS, ¶ms)) {
LOGE(LOG_TAG, "%s:%d, cannot set hw params", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
LOGD(LOG_TAG, "%s:%d, block %d, interleave %d, rate %d channels %d bits %d", __func__, __LINE__, params.block,
params.interleave, params.rate, params.channels, params.sample_bits);
return ret;
}
int aos_pcm_sw_params_any(aos_pcm_sw_params_t *params)
{
if(!params) {
return PCM_RETURN_ERR;
}
params->period_step = 20; // 20ms period by default
return PCM_RETURN_SUCCESS;
}
int aos_pcm_sw_params_alloca(aos_pcm_sw_params_t **p)
{
*p = (aos_pcm_sw_params_t *)calloc(1, sizeof(aos_pcm_sw_params_t));
if(NULL == *p) {
LOGE(LOG_TAG, "%s:%d, calloc aos_pcm_sw_params_t failed", __func__, __LINE__);
return -ENOMEM;
}
return PCM_RETURN_SUCCESS;
}
int aos_pcm_sw_params(aos_pcm_t *pcm, aos_pcm_sw_params_t *p)
{
int ret = PCM_RETURN_SUCCESS;
audio_sw_params_t params;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->sw_params && p) {
pcm->sw_params->period_step = p->period_step;
} else {
LOGE(LOG_TAG, "%s:%d, invalid pcm->sw_params or p", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
params.hdl = &pcm->evt;
params.period = p->period_step;
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_SW_PARAMS, ¶ms)) {
LOGE(LOG_TAG, "%s:%d, cannot set sw params", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
return ret;
}
int aos_pcm_set_params(aos_pcm_t *pcm, aos_pcm_format_t format, aos_pcm_access_t access, unsigned int channels,
unsigned int rate, int soft_resample, unsigned int latency)
{
int ret = PCM_RETURN_SUCCESS;
audio_hw_params_t params;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if (!pcm->hw_params) {
pcm->hw_params = aos_zalloc(sizeof(aos_pcm_hw_params_t));
if (pcm->hw_params == NULL) {
return PCM_RETURN_ERR;
}
}
pcm->hw_params->access = access;
pcm->hw_params->channels = channels;
pcm->hw_params->format = format;
pcm->hw_params->rate = rate;
pcm->hw_params->sample_bits = format * 8;
pcm->hw_params->frame_bits = format * 8 * channels;
params.block = (pcm->mode & AOS_PCM_NONBLOCK) ? 0 : 1;
params.interleave = (access == AOS_PCM_ACCESS_RW_NONINTERLEAVED) ? 0 : 1;
params.channels = channels;
params.rate = rate;
switch(format) {
case AOSRV_PCM_FORMAT_S8:
params.sample_bits = 8;
break;
case AOSRV_PCM_FORMAT_S16_LE:
params.sample_bits = 16;
break;
case AOSRV_PCM_FORMAT_S24_LE:
params.sample_bits = 24;
break;
case AOSRV_PCM_FORMAT_S32_LE:
params.sample_bits = 32;
break;
default:
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_HW_PARAMS, ¶ms)) {
LOGE(LOG_TAG, "%s:%d, cannot set hw params", __func__, __LINE__);
ret = PCM_RETURN_ERR;
}
PCM_UNLOCK(pcm);
LOGD(LOG_TAG, "%s:%d, block %d, interleave %d, rate %d channels %d bits %d", __func__, __LINE__, params.block,
params.interleave, params.rate, params.channels, params.sample_bits);
return ret;
}
aos_pcm_sframes_t aos_pcm_writei(aos_pcm_t *pcm, const void *buffer, aos_pcm_uframes_t size)
{
audio_xferi_t x;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->state != AOS_PCM_STATE_RUNNING) {
LOGE(LOG_TAG, "%s:%d, unexpected pcm state %d", __func__, __LINE__, pcm->state);
return PCM_RETURN_ERR;
}
if(pcm->stream != AOS_PCM_STREAM_PLAYBACK) {
LOGE(LOG_TAG, "%s:%d, not playback device", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
x.buf = (void*)buffer;
x.frames = size;
x.result = 0;
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_WRITEI_FRAMES, &x)) {
LOGE(LOG_TAG, "%s:%d, ioctl writei failed", __func__, __LINE__);
}
PCM_UNLOCK(pcm);
//LOGE(LOG_TAG, "%s:%d, frames %d result %d", __func__, __LINE__, x.frames, x.result);
return x.result;
}
aos_pcm_sframes_t aos_pcm_writen(aos_pcm_t *pcm, void **bufs, aos_pcm_uframes_t size)
{
audio_xfern_t x;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->state != AOS_PCM_STATE_RUNNING) {
LOGE(LOG_TAG, "%s:%d, unexpected pcm state %d", __func__, __LINE__, pcm->state);
return PCM_RETURN_ERR;
}
if(pcm->stream != AOS_PCM_STREAM_PLAYBACK) {
LOGE(LOG_TAG, "%s:%d, not playback device", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
x.bufs = bufs;
x.frames = size;
x.result = 0;
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_WRITEN_FRAMES, &x)) {
LOGE(LOG_TAG, "%s:%d, ioctl writen failed", __func__, __LINE__);
}
PCM_UNLOCK(pcm);
//LOGE(LOG_TAG, "%s:%d, frames %d result %d", __func__, __LINE__, x.frames, x.result);
return x.result;
}
aos_pcm_sframes_t aos_pcm_readi(aos_pcm_t *pcm, void *buffer, aos_pcm_uframes_t size)
{
audio_xferi_t x;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->state != AOS_PCM_STATE_RUNNING) {
LOGE(LOG_TAG, "%s:%d, unexpected pcm state %d", __func__, __LINE__, pcm->state);
return PCM_RETURN_ERR;
}
if(pcm->stream != AOS_PCM_STREAM_CAPTURE) {
LOGE(LOG_TAG, "%s:%d, not capture device", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
x.buf = (void*)buffer;
x.frames = size;
x.result = 0;
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_READI_FRAMES, &x)) {
LOGE(LOG_TAG, "%s:%d, ioctl readi failed", __func__, __LINE__);
}
PCM_UNLOCK(pcm);
return x.result;
}
aos_pcm_sframes_t aos_pcm_readn(aos_pcm_t *pcm, void **bufs, aos_pcm_uframes_t size)
{
audio_xfern_t x;
if(NULL == pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->fd < 0) {
LOGE(LOG_TAG, "%s:%d, param fd is not opened", __func__, __LINE__);
return PCM_RETURN_ERR;
}
if(pcm->state != AOS_PCM_STATE_RUNNING) {
LOGE(LOG_TAG, "%s:%d, unexpected pcm state %d", __func__, __LINE__, pcm->state);
return PCM_RETURN_ERR;
}
if(pcm->stream != AOS_PCM_STREAM_CAPTURE) {
LOGE(LOG_TAG, "%s:%d, not capture device", __func__, __LINE__);
return PCM_RETURN_ERR;
}
PCM_LOCK(pcm);
x.bufs = bufs;
x.frames = size;
x.result = 0;
if(ioctl(pcm->fd, AUDIO_PCM_IOCTL_READN_FRAMES, &x)) {
LOGE(LOG_TAG, "%s:%d, ioctl readn failed", __func__, __LINE__);
}
PCM_UNLOCK(pcm);
return x.result;
}
aos_pcm_sframes_t aos_pcm_bytes_to_frames(aos_pcm_t *pcm, int bytes)
{
if(!pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
return (bytes / (pcm->hw_params->frame_bits / 8));
}
int aos_pcm_frames_to_bytes(aos_pcm_t *pcm, aos_pcm_sframes_t frames)
{
if(!pcm) {
LOGE(LOG_TAG, "%s:%d, param pcm is null", __func__, __LINE__);
return PCM_RETURN_ERR;
}
return (frames * (pcm->hw_params->frame_bits / 8));
} | YifuLiu/AliOS-Things | components/a2sa/src/framework/sound_pcm.c | C | apache-2.0 | 21,159 |
/*
* Copyright (C) 2015-2021 Alibaba Group Holding Limited
*/
#include "aiagent_service.h"
#include "aiagent_common.h"
#include "ulog/ulog.h"
#if AOS_COMP_CLI
#include "aos/cli.h"
#endif
#define TAG "aiagent_example"
#define LOG printf
#ifdef CONFIG_ALICLOUD_FACEBODY_ENABLE
static int facebody_compare_callback(ai_result_t *result)
{
float confidence;
int x, y, w, h;
if (!result)
return -1;
confidence = result->facebody.face.confidence;
x = result->facebody.face.location.x;
y = result->facebody.face.location.y;
w = result->facebody.face.location.w;
h = result->facebody.face.location.h;
LOG("Facebody comparing result:\n");
LOG("confidence: %.1f\n", confidence);
LOG("location at x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
return 0;
}
static int recognize_expression_callback(ai_result_t *result)
{
int len;
char *expression = NULL;
float face_probability;
if (!result)
return -1;
expression = result->facebody.expression.expression;
face_probability = result->facebody.expression.probability;
if (!expression && strlen(expression) > 0)
return -1;
LOG("Recognize expression result:\n");
LOG("type: %s, probability: %.1f\n", expression, face_probability);
return 0;
}
static int generate_human_anime_styple_callback(ai_result_t *result)
{
int ret;
char *url = NULL;
if (!result)
return -1;
LOG("Generate human anime style result:\n");
url = result->facebody.anime.url;
if (!url && strlen(url) > 0)
return -1;
LOG("url: %s\n", url);
return ret;
}
#endif
#ifdef CONFIG_ALICLOUD_OBJECTDET_ENABLE
static int detect_object_callback(ai_result_t *result)
{
int len = 0;
int x, y, w, h;
char *type = NULL;
float score;
if (!result)
return -1;
LOG("Detect object result:\n");
type = result->objectdet.object.type;
score = result->objectdet.object.score;
x = result->objectdet.object.box.x;
y = result->objectdet.object.box.y;
w = result->objectdet.object.box.w;
h = result->objectdet.object.box.h;
if (!type) {
LOGE(TAG, "type is null\n");
return -1;
}
LOG("type: %s, Score: %.1f, x: %d, y: %d, w: %d, h: %d\n", type, score, x, y, w, h);
return 0;
}
static int detect_main_body_callback(ai_result_t *result)
{
int x, y, w, h;
if (!result)
return -1;
x = result->objectdet.mainbody.location.x;
y = result->objectdet.mainbody.location.y;
w = result->objectdet.mainbody.location.w;
h = result->objectdet.mainbody.location.h;
LOG("Detect main body result:\n");
LOG("main body location x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
return 0;
}
#endif
#ifdef CONFIG_ALICLOUD_IMAGESEG_ENABLE
static int segment_common_image_callback(ai_result_t *result)
{
int ret;
char *url = NULL;
int x, y, w, h;
if (!result)
return -1;
LOG("Segment common image result:\n");
url = result->imageseg.common.url;
if (!url && strlen(url) > 0)
return -1;
LOG("url: %s\n", url);
return 0;
}
static int segment_face_callback(ai_result_t *result)
{
int ret;
int image_len = 0;
int x, y, w, h;
char *url = NULL;
char path[32] = {0};
if (!result)
return -1;
LOG("Segment face result:\n");
url = result->imageseg.face.url;
x = result->imageseg.face.location.x;
y = result->imageseg.face.location.y;
w = result->imageseg.face.location.w;
h = result->imageseg.face.location.h;
if (!url && strlen(url) > 0)
return -1;
LOG("image url: %s\n", url);
LOG("location at x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
return 0;
}
#endif
#ifdef CONFIG_ALICLOUD_OCR_ENABLE
static int recognize_identity_card_face_side_callback(ai_result_t *result)
{
char *address = NULL;
char *birthdate = NULL;
char *gender = NULL;
char *nationality = NULL;
char *id_num = NULL;
int card_x[4], card_y[4], face_x[4], face_y[4];
if (!result)
return -1;
LOG("Recognize identity card face side result:\n");
/*address string*/
address = result->ocr.identity.face.address;
if (address && strlen(address) > 0)
LOG("address: %s\n", address);
/*birthdate string*/
birthdate = result->ocr.identity.face.birthDate;
if (birthdate && strlen(birthdate) > 0)
LOG("birthdate: %s\n", birthdate);
/*gender string*/
gender = result->ocr.identity.face.gender;
if (gender && strlen(gender) > 0)
LOG("gender: %s\n", gender);
/*nationality string*/
nationality = result->ocr.identity.face.nationality;
if (nationality && strlen(nationality) > 0)
LOG("nationality: %s\n", nationality);
/*id number string*/
id_num = result->ocr.identity.face.iDNumber;
if (id_num && strlen(id_num) > 0)
LOG("id number: %s\n", id_num);
/*card box line*/
memcpy(card_x, result->ocr.identity.face.cardX, 4);
memcpy(card_y, result->ocr.identity.face.cardY, 4);
if (card_x && card_y) {
LOG("card location: x0: %d, y0: %d\n", card_x[0], card_x[0]);
LOG("card location: x1: %d, y1: %d\n", card_x[1], card_x[1]);
LOG("card location: x2: %d, y2: %d\n", card_x[2], card_x[2]);
LOG("card location: x3: %d, y3: %d\n", card_x[3], card_x[3]);
}
/*face box line*/
memcpy(face_x, result->ocr.identity.face.faceX, 4);
memcpy(face_y, result->ocr.identity.face.faceY, 4);
if (face_x && face_y) {
LOG("face location: x0: %d, y0: %d\n", card_x[0], card_x[0]);
LOG("face location: x1: %d, y1: %d\n", card_x[1], card_x[1]);
LOG("face location: x2: %d, y2: %d\n", card_x[2], card_x[2]);
LOG("face location: x3: %d, y3: %d\n", card_x[3], card_x[3]);
}
return 0;
}
static int recognize_identity_card_back_side_callback(ai_result_t *result)
{
char *start_date = NULL;
char *issue = NULL;
char *end_date = NULL;
if (!result)
return -1;
LOG("Recognize identity card back side result:\n");
/*start date of identity card's back side*/
start_date = result->ocr.identity.back.startDate;
if (start_date && strlen(start_date) > 0)
LOG("start date: %s\n", start_date);
/*issue of identity card's back side*/
issue = result->ocr.identity.back.issue;
if (issue && strlen(issue) > 0)
LOG("issue: %s\n", issue);
/*end date of identity card's back side*/
end_date = result->ocr.identity.back.endDate;
if (end_date && strlen(end_date) > 0)
LOG("end date: %s\n", end_date);
return 0;
}
static int recognize_bank_card_callback(ai_result_t *result)
{
char *bank_name = NULL;
char *card_number = NULL;
char *valid_date = NULL;
if (!result)
return -1;
LOG("Recognize bank card result:\n");
/*bank name of bank card*/
bank_name = result->ocr.bank.bankName;
if (bank_name && strlen(bank_name) > 0)
LOG("bank name: %s\n", bank_name);
/*card number of bank card*/
card_number = result->ocr.bank.cardNumber;
if (card_number && strlen(card_number) > 0)
LOG("card number: %s\n", card_number);
/*valid date of bank card*/
valid_date = result->ocr.bank.validDate;
if (valid_date && strlen(valid_date) > 0)
LOG("valid date: %s\n", valid_date);
return 0;
}
static int recognize_character_callback(ai_result_t *result)
{
float probability;
char *text = NULL;
int left, top;
int width, height;
if (!result)
return -1;
LOG("Recognize character result:\n");
text = result->ocr.character.text;
left = result->ocr.character.left;
top = result->ocr.character.top;
width = result->ocr.character.width;
height = result->ocr.character.height;
probability = result->ocr.character.probability;
if (text) {
LOG("text: %s\n", text);
LOG("probability: %.1f\n", probability);
LOG("text area: left: %d, top: %d, weight: %d, height: %d\n", top, left, width, height);
}
return 0;
}
#endif
#ifdef CONFIG_ALICLOUD_IMAGERECOG_ENABLE
static int imagerecog_classifying_rubbish_callback(ai_result_t *result)
{
char *rubbish = NULL;
char *category = NULL;
float rubbish_score;
float category_score;
if (!result)
return -1;
LOG("Recognize rubbish result:\n");
/*rubbish name*/
rubbish = result->imagerecog.rubbish.rubbish;
rubbish_score = result->imagerecog.rubbish.rubbishScore;
if (rubbish && strlen(rubbish) > 0) {
LOG("rubbish: %s\n", rubbish);
LOG("rubbish score: %.1f\n", rubbish_score);
}
/*rubbish category*/
category = result->imagerecog.rubbish.category;
category_score = result->imagerecog.rubbish.categoryScore;
if (category && strlen(category) > 0) {
LOG("category: %s\n", category);
LOG("category score: %.1f\n", category_score);
}
return 0;
}
static int imagerecog_detect_fruits_callback(ai_result_t *result)
{
char score_str[8];
char *name = NULL;
int tmp_y, x, y, w, h;
float score;
if (!result)
return -1;
LOG("Recognize fruits result:\n");
/*fruits name and score*/
name = result->imagerecog.fruits.name;
score = result->imagerecog.fruits.score;
x = result->imagerecog.fruits.box.x;
y = result->imagerecog.fruits.box.y;
w = result->imagerecog.fruits.box.w;
h = result->imagerecog.fruits.box.h;
if (name && strlen(name) > 0) {
LOG("fruit name: %s\n", name);
LOG("fruit score: %.1f\n", score);
LOG("fruit location: x: %d, y: %d, w: %d, h: %d\n", x, y, w, h);
}
return 0;
}
#endif
#ifdef CONFIG_ALICLOUD_IMAGEENHAN_ENABLE
static int imageenhan_erase_person_callback(ai_result_t *result)
{
int ret;
char *url = NULL;
if (!result)
return -1;
LOG("Erase person result:\n");
url = result->imageenhan.person.url;
LOG("url: %s\n", url);
return 0;
}
static int imageenhan_extend_image_style_callback(ai_result_t *result)
{
int ret;
int major_image_len = 0;
int out_image_len = 0;
char *major_url = NULL;
char *out_image_url = NULL;
char *p_major_url = NULL;
char *p_out_image_url = NULL;
if (!result)
return -1;
major_url = result->imageenhan.style.majorUrl;
out_image_url = result->imageenhan.style.outImageUrl;
LOG("Extend image style result:\n");
if (major_url && strlen(major_url) > 0) {
LOG("major url: %s\n", major_url);
}
if (out_image_url && strlen(out_image_url) > 0) {
LOG("out image url: %s\n", out_image_url);
}
return 0;
}
#endif // UCLOUD_AI_IMAGERECOG_CONFIG
static void aiagent_comp_example(int argc, char **argv)
{
int model_index = -1;
int ret = -1;
char *image1 = NULL;
char *image2 = NULL;
ai_engine_cb_t cb;
if (argc < 4) {
LOG("Please test with command: aiagent_example -m [0~14]\n");
return;
}
if (!strncmp(argv[1], "-e", 2)) {
if (strncmp(argv[2], "ucloud-ai", 9)) {
LOG("not support ai engine, currently we support ucloud-ai engine\n");
return;
}
} else {
LOG("unkown %d command\n", argv[1]);
return;
}
if (!strncmp(argv[3], "init", 4)) {
/*init network*/
event_service_init(NULL);
netmgr_service_init(NULL);
LOG("aiagent init successfully!\n");
return;
} else if (!strncmp(argv[3], "-m", 2)) {
model_index = atoi(argv[4]);
if (model_index < 0 && model_index > 14) {
LOGE(TAG, "range of model value is 0 ~ 14, please try again\n");
return;
}
} else {
LOG("unkown command\n");
return;
}
ret = aiagent_service_init(argv[2], model_index);
if (ret < 0) {
LOGE(TAG, "aiagent service init fail, ret:%d\r\n", ret);
return;
}
/*get callback function based on current model*/
switch (aiagent_service_get_cur_model()) {
#ifdef CONFIG_ALICLOUD_FACEBODY_ENABLE
case AI_MODEL_COMPARING_FACEBODY:
cb = facebody_compare_callback;
image1 = FACE1_IMAGE;
image2 = FACE2_IMAGE;
break;
case AI_MODEL_GENERATE_HUMAN_ANIME_STYLE:
cb = generate_human_anime_styple_callback;
image1 = ANIME_IMAGE;
image2 = NULL;
break;
case AI_MODEL_RECOGNIZE_EXPRESSION:
cb = recognize_expression_callback;
image1 = EXPRESSION_IMAGE;
image2 = NULL;
break;
break;
#endif
#ifdef CONFIG_ALICLOUD_OBJECTDET_ENABLE
case AI_MODEL_DETECT_OBJECT:
cb = detect_object_callback;
image1 = OBJECT_IMAGE;
image2 = NULL;
break;
case AI_MODEL_DETECT_MAIN_BODY:
cb = detect_main_body_callback;
image1 = MAINBODY_IMAGE;
image2 = NULL;
break;
#endif
#ifdef CONFIG_ALICLOUD_IMAGESEG_ENABLE
case AI_MODEL_SEGMENT_COMMON_IMAGE:
cb = segment_common_image_callback;
image1 = MAINBODY_IMAGE;
image2 = NULL;
break;
case AI_MODEL_SEGMENT_FACE:
cb = segment_face_callback;
image1 = FACE1_IMAGE;
image2 = NULL;
break;
#endif
#ifdef CONFIG_ALICLOUD_OCR_ENABLE
case AI_MODEL_RECOGNIZE_IDENTITY_CARD_FACE_SIDE:
cb = recognize_identity_card_face_side_callback;
image1 = CARD_FACE_IMAGE;
image2 = NULL;
break;
case AI_MODEL_RECOGNIZE_IDENTITY_CARD_BACK_SIDE:
cb = recognize_identity_card_back_side_callback;
image1 = CARD_BACK_IMAGE;
image2 = NULL;
break;
case AI_MODEL_RECOGNIZE_BANK_CARD:
cb = recognize_bank_card_callback;
image1 = BANK_CARD_IMAGE;
image2 = NULL;
break;
case AI_MODEL_RECOGNIZE_CHARACTER:
cb = recognize_character_callback;
image1 = CHARACTER_IMAGE;
image2 = NULL;
break;
#endif
#ifdef CONFIG_ALICLOUD_IMAGERECOG_ENABLE
case AI_MODEL_CLASSIFYING_RUBBISH:
cb = imagerecog_classifying_rubbish_callback;
image1 = RUBBISH_IMAGE;
image2 = NULL;
break;
case AI_MODEL_DETECT_FRUITS:
cb = imagerecog_detect_fruits_callback;
image1 = FRUITS_IMAGE;
image2 = NULL;
break;
#endif
#ifdef CONFIG_ALICLOUD_IMAGEENHAN_ENABLE
case AI_MODEL_ERASE_PERSON:
cb = imageenhan_erase_person_callback;
image1 = PERSON_ORG_IMAGE;
image2 = NULL;
break;
case AI_MODEL_EXTEND_IMAGE_STYLE:
cb = imageenhan_extend_image_style_callback;
image1 = STYLE_IMAGE;
image2 = NULL;
break;
#endif
default:
cb = NULL;
image1 = NULL;
image2 = NULL;
break;
}
/*do ai model inference*/
if (cb)
aiagent_service_model_infer(image1, image2, (ai_engine_cb_t)cb);
ret = aiagent_service_uninit();
if (ret < 0) {
LOGE(TAG, "aiagent_service_uninit fail, ret:%d\r\n", ret);
return;
}
return;
}
#if AOS_COMP_CLI
/* reg args: fun, cmd, description*/
ALIOS_CLI_CMD_REGISTER(aiagent_comp_example, aiagent, aiagent component base example)
#endif
| YifuLiu/AliOS-Things | components/ai_agent/example/aiagent_example.c | C | apache-2.0 | 15,570 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#ifndef _AI_AGENT_COMMON_H_
#define _AI_AGENT_COMMON_H_
#include <stdint.h>
#ifdef CONFIG_UCLOUD_AI_ENGINE_ENABLE
#include "ucloud_ai_common.h"
typedef ucloud_ai_result_t ai_result_t;
typedef void *ai_config_t;
#elif defined(CONFIG_KWS_AI_ENGINE_ENABLE)
#include "engine/kws_engine.h"
typedef int32_t ai_result_t;
typedef kws_engine_config_t ai_config_t;
#else
typedef void *ai_result_t;
typedef void *ai_config_t;
#endif
typedef enum _ai_model_t {
AI_MODEL_COMPARING_FACEBODY, // 人脸比对
AI_MODEL_GENERATE_HUMAN_ANIME_STYLE, // 人物动漫化
AI_MODEL_RECOGNIZE_EXPRESSION, // 表情识别
AI_MODEL_DETECT_OBJECT, // 目标检测
AI_MODEL_DETECT_MAIN_BODY, // 主体检测
AI_MODEL_SEGMENT_COMMON_IMAGE, // 通用分割
AI_MODEL_SEGMENT_FACE, // 人脸分割
AI_MODEL_RECOGNIZE_IDENTITY_CARD_FACE_SIDE, // 身份证正面识别
AI_MODEL_RECOGNIZE_IDENTITY_CARD_BACK_SIDE, // 身份证背面识别
AI_MODEL_RECOGNIZE_BANK_CARD, // 银行卡识别
AI_MODEL_RECOGNIZE_CHARACTER, // 文本识别
AI_MODEL_CLASSIFYING_RUBBISH, // 垃圾分类
AI_MODEL_DETECT_FRUITS, // 水果检测
AI_MODEL_ERASE_PERSON, // 图像人体擦除
AI_MODEL_EXTEND_IMAGE_STYLE, // 风格迁移
AI_MODEL_KWS, // 语音唤醒
AI_MODEL_MAX
} ai_model_t;
typedef int (*ai_engine_cb_t)(ai_result_t *result);
#endif // _AI_AGENT_COMMON_H_
| YifuLiu/AliOS-Things | components/ai_agent/include/aiagent_common.h | C | apache-2.0 | 1,717 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#ifndef _AI_AGENT_ENGINE_H_
#define _AI_AGENT_ENGINE_H_
#include <stdint.h>
#include <stdbool.h>
#include "aiagent_common.h"
#ifdef CONFIG_UCLOUD_AI_ENGINE_ENABLE
#include "engine/ucloud_ai_engine.h"
#endif
typedef struct _aiagent_engine_t {
/* * * */
/* The name of this ucloud ai engine */
const char *name;
bool is_dummy; /*if no engine, use dummy*/
ai_model_t model;
char *src1; /*source data1*/
char *src2; /*source data2, some cases need two image to compare*/
ai_engine_cb_t callback;
ai_config_t *config;
/*init ai engine*/
int32_t (*ai_engine_init) (struct _aiagent_engine_t *eng);
/*uninit ai engine*/
void (*ai_engine_uninit) (struct _aiagent_engine_t *eng);
/*config ai engine*/
void (*ai_engine_config) (struct _aiagent_engine_t *eng);
/*run ai engine model*/
int32_t (*ai_engine_model_infer) (struct _aiagent_engine_t *eng);
/*free ai engine*/
void (*ai_engine_free) (struct _aiagent_engine_t *eng);
} aiagent_engine_t;
#endif // _AI_AGENT_ENGINE_H_
| YifuLiu/AliOS-Things | components/ai_agent/include/aiagent_engine.h | C | apache-2.0 | 1,115 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#ifndef _AI_AGENT_H_
#define _AI_AGENT_H_
#include "aiagent_engine.h"
#include "aiagent_common.h"
typedef struct _aiagent_context_t {
const char *name;
const char *desc;
int (*available) (void);
aiagent_engine_t *(*create) (int engineid);
} aiagent_context_t;
/** @defgroup aiagent_aos_api aiagent
* @{
*/
/**
* Initialize aiagent service.
* @param[in] engine_name engine name.
* @param[in] model ai model.
*
* @return 0 on success, negative error on failure.
*/
int32_t aiagent_service_init(const char *engine_name, ai_model_t model);
/**
* Uninitialize aiagent service.
*
* @return 0 on success, negative error on failure.
*/
int32_t aiagent_service_uninit(void);
/**
* Config the aiagent service.
* @param[in] config ai engine config.
*
* @return 0 on success, negative error on failure.
*/
void aiagent_service_config(ai_config_t *config);
/**
* Init the aiagent service.
* @param[in] src1 source data1(image) you want to detect.
* @param[in] src2 source data2(image), some cases need to compare with original data.
* @param[in] cb callback function to deal with result.
*
* @return 0 on success, negative error on failure.
*/
int32_t aiagent_service_model_infer(char *src1, char *src2, ai_engine_cb_t cb);
/**
* Init the aiagent service.
*
* @return ai model get frome aiagent service.
*/
ai_model_t aiagent_service_get_cur_model(void);
/**
* @}
*/
#endif // _AI_AGENT_H_
| YifuLiu/AliOS-Things | components/ai_agent/include/aiagent_service.h | C | apache-2.0 | 1,531 |
/*
* Copyright (C) 2020-2023 Alibaba Group Holding Limited
*/
#ifndef _AI_CONFIG_H_
#define _AI_CONFIG_H_
// Choose AI Capability
#define AI_MODEL AI_MODEL_COMPARING_FACEBODY
#endif // _AI_CONFIG_H_
| YifuLiu/AliOS-Things | components/ai_agent/include/aiconfig.h | C | apache-2.0 | 204 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#ifndef _KWS_ENGINE_H_
#define _KWS_ENGINE_H_
#define KWS_NAME "kws"
typedef void *kws_engine_cb_t;
typedef struct {
int8_t channel;
} kws_engine_config_t;
#endif // _KWS_ENGINE_H_
| YifuLiu/AliOS-Things | components/ai_agent/include/engine/kws_engine.h | C | apache-2.0 | 253 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#ifndef _UCLOUD_AI_ENGINE_H_
#define _UCLOUD_AI_ENGINE_H_
#define UCLOUD_AI_NAME "ucloud-ai"
#endif // _UCLOUD_AI_ENGINE_H_
| YifuLiu/AliOS-Things | components/ai_agent/include/engine/ucloud_ai_engine.h | C | apache-2.0 | 192 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include "ulog/ulog.h"
#include "aos/kernel.h"
#include "aiconfig.h"
#include "aiagent_service.h"
#ifdef CONFIG_UCLOUD_AI_ENGINE_ENABLE
#include "engine/ucloud_ai_engine.h"
#endif
#ifdef CONFIG_KWS_AI_ENGINE_ENABLE
#include "engine/kws_engine.h"
#endif
#define TAG "AIAGENT_ENGINE"
static aiagent_engine_t *g_ai_engine = NULL;
#ifdef CONFIG_UCLOUD_AI_ENGINE_ENABLE
extern aiagent_context_t ucloud_ai_engine;
#endif
#ifdef CONFIG_KWS_AI_ENGINE_ENABLE
extern aiagent_context_t kws_engine;
#endif
/* Available ai engine context */
static aiagent_context_t *ai_engine_ctx[] = {
#ifdef CONFIG_UCLOUD_AI_ENGINE_ENABLE
&ucloud_ai_engine,
#endif
#ifdef CONFIG_KWS_AI_ENGINE_ENABLE
&kws_engine,
#endif
NULL
};
/*
* Initialize the ai engine
*/
aiagent_engine_t *aiagent_engine_init(const char *dev_name)
{
aiagent_engine_t *engine;
int32_t index;
int32_t i;
/*Reset ai engine service*/
if (g_ai_engine != NULL)
aiagent_engine_uninit();
index = 0;
engine = NULL;
if (dev_name == NULL)
return NULL;
if (dev_name != NULL) {
for (i = 0; ai_engine_ctx[i]; ++i) {
if (strncasecmp(ai_engine_ctx[i]->name, dev_name, strlen(dev_name)) == 0) {
if (ai_engine_ctx[i]->available()) {
engine = ai_engine_ctx[i]->create(index);
break;
}
}
}
} else {
for (i = 0; ai_engine_ctx[i]; ++i) {
if (ai_engine_ctx[i]->available()) {
engine = ai_engine_ctx[i]->create(index);
if (engine != NULL)
break;
}
}
}
if (engine == NULL) {
if (dev_name) {
LOGE(TAG, "%s not available", dev_name);
return NULL;
}
LOGE(TAG, "No available engine engine");
return NULL;
}
g_ai_engine = engine;
g_ai_engine->name = ai_engine_ctx[i]->name;
/* Initialize the ai engine */
if (g_ai_engine->ai_engine_init(g_ai_engine) < 0) {
aiagent_engine_uninit();
return NULL;
}
LOG("Initialize ai agent engine successfully\n");
return g_ai_engine;
}
/*
* Uninitialize the ai engine
*/
void aiagent_engine_uninit(void)
{
int32_t i, j;
if (!g_ai_engine)
return;
g_ai_engine->ai_engine_uninit(g_ai_engine);
g_ai_engine->ai_engine_free(g_ai_engine);
g_ai_engine = NULL;
LOG("Uninitialize ai agent engine successfully\n");
return;
}
void aiagent_engine_config(ai_config_t *config)
{
g_ai_engine->config = config;
g_ai_engine->ai_engine_config(g_ai_engine);
}
const char *aiagent_get_engine_name(void)
{
if (!g_ai_engine)
return NULL;
return g_ai_engine->name;
}
aiagent_engine_t *aiagent_get_engine(void)
{
return g_ai_engine;
}
| YifuLiu/AliOS-Things | components/ai_agent/src/aiagent_engine.c | C | apache-2.0 | 2,935 |
/*
* Copyright (C) 2021-2023 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include "ulog/ulog.h"
#include "aos/kernel.h"
#include "aiconfig.h"
#include "aiagent_service.h"
#include "aiagent_engine.h"
#define TAG "AIAGENT_SERVICE"
/*
* Initialize the ai agent service
*/
int32_t aiagent_service_init(const char *engine_name, ai_model_t model)
{
aiagent_engine_t *eng = aiagent_engine_init(engine_name);
if (!eng) {
LOGE(TAG, "ai agent service init fail\n");
return -1;
}
eng->model = model;
return 0;
}
/*
* Uninitialize the ai agent service
*/
int32_t aiagent_service_uninit(void)
{
return aiagent_engine_uninit();
}
/*
* Config the ai agent service
*/
void aiagent_service_config(ai_config_t *config)
{
aiagent_engine_config(config);
}
/*
* Do ai vision model inference
*/
int32_t aiagent_service_model_infer(char *src1, char *src2, ai_engine_cb_t cb)
{
int32_t ret;
aiagent_engine_t *eng = aiagent_get_engine();
if (!eng) {
LOGE(TAG, "aiagent get engine name fail\n");
return -1;
}
eng->callback = cb;
eng->src1 = src1;
eng->src2 = src2;
ret = eng->ai_engine_model_infer(eng);
LOG("aiagent_service_model_infer done\n");
return ret;
}
/*
* Get current ai agent model
*/
ai_model_t aiagent_service_get_cur_model(void)
{
aiagent_engine_t *eng = aiagent_get_engine();
if (!eng) {
LOGE(TAG, "aiagent get engine name fail\n");
return -1;
}
return eng->model;
}
| YifuLiu/AliOS-Things | components/ai_agent/src/aiagent_service.c | C | apache-2.0 | 1,539 |
#include "aos/kernel.h"
#include "speech_memory.h"
#include "aqe_kws.h"
#include "mcu_audio.h"
#include "ulog/ulog.h"
#include "aiagent_engine.h"
#include "aiagent_service.h"
#include "engine/kws_engine.h"
#include "a7_cmd.h"
#define TAG "kws"
AqeKwsConfig kws_cfg;
AqeKwsState *kws_st = NULL;
uint32_t kws_cnt = 0;
static bool kws_running = false;
static aiagent_engine_t *eng = NULL;
static aos_task_t kws_task_handle;
static aos_sem_t kws_sem;
static int32_t kws_ret = 1;
static int8_t kws_channel = 0;
static bool kws_exited = false;
static bool kws_inited = false;
static void callback_main(void *p)
{
kws_running = true;
kws_exited = false;
while (1) {
aos_sem_wait(&kws_sem, AOS_WAIT_FOREVER);
if (kws_running) {
if (eng->callback)
eng->callback((ai_result_t)&kws_ret);
else
LOG("callback is not set\n");
}
else
break;
}
kws_exited = true;
}
static void my_kws_process(uint8_t *buf, uint32_t len)
{
int32_t r = 0, w = 0;
int16_t thres_tmp[1] = {60};
A7_CMD_T *cmd = (A7_CMD_T *)buf;
if (kws_exited)
return;
if ((cmd->p1 == 1) && (cmd->p2 == 1)) {
LOG("wakeup\n");
aos_sem_signal(&kws_sem);
}
}
int32_t kws_engine_init(aiagent_engine_t *eng)
{
if (!eng)
return -1;
/*enable dsp kws*/
enable_a7_kws(1);
if (!kws_inited) {
aos_sem_new(&kws_sem, 0);
set_a7_cmd_callback_handler(my_kws_process);
kws_inited = true;
LOGI(TAG, "aos_task_new_ext kws_task\n");
}
return 0;
}
static void kws_engine_delete(aiagent_engine_t *eng)
{
if (!eng)
return;
free(eng);
}
static bool kws_engine_available(void)
{
return true;
}
int32_t kws_engine_uninit(aiagent_engine_t *eng)
{
int32_t ret;
if (!eng)
return -1;
/*enable dsp kws*/
enable_a7_kws(0);
kws_running = false;
aos_sem_signal(&kws_sem);
while (!kws_exited) {
aos_msleep(50);
}
aos_task_delete(&kws_task_handle);
kws_st = NULL;
LOGI(TAG, "aos_task_delete kws_task\n");
return 0;
}
int32_t kws_engine_config(aiagent_engine_t *eng)
{
kws_engine_config_t *config;
config = (kws_engine_config_t *)eng->config;
kws_channel = config->channel;
}
int32_t kws_engine_model_infer(aiagent_engine_t *eng)
{
if (!eng)
return -1;
aos_task_new_ext(&kws_task_handle,
"kws_callback", callback_main,
NULL, 1024 * 120, AOS_DEFAULT_APP_PRI);
return 0;
}
static aiagent_engine_t *kws_engine_create(int engineid)
{
/* Malloc ai agent eng*/
eng = (aiagent_engine_t *) malloc(sizeof(aiagent_engine_t));
if (!eng) {
LOGE(TAG, "malloc camera device fail\n");
return NULL;
}
eng->is_dummy = false;
/* Set the function pointers */
eng->ai_engine_init = kws_engine_init;
eng->ai_engine_uninit = kws_engine_uninit;
eng->ai_engine_config = kws_engine_config;
eng->ai_engine_model_infer = kws_engine_model_infer;
eng->ai_engine_free = kws_engine_delete;
return eng;
}
aiagent_context_t kws_engine = {
KWS_NAME, "kws(keyword spotting) engine",
kws_engine_available, kws_engine_create
};
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/kws_engine.c | C | apache-2.0 | 3,262 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
/// \file
/// Memory management for TF Lite.
#ifndef TENSORFLOW_LITE_ALLOCATION_H_
#define TENSORFLOW_LITE_ALLOCATION_H_
#include <stddef.h>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include "tensorflow/lite/core/api/error_reporter.h"
namespace tflite {
// A memory allocation handle. This could be a mmap or shared memory.
class Allocation {
public:
virtual ~Allocation() {}
enum class Type {
kMMap,
kFileCopy,
kMemory,
};
// Base pointer of this allocation
virtual const void* base() const = 0;
// Size in bytes of the allocation
virtual size_t bytes() const = 0;
// Whether the allocation is valid
virtual bool valid() const = 0;
// Return the type of the Allocation.
Type type() const { return type_; }
protected:
Allocation(ErrorReporter* error_reporter, Type type)
: error_reporter_(error_reporter), type_(type) {}
ErrorReporter* error_reporter_;
private:
const Type type_;
};
// Note that not all platforms support MMAP-based allocation.
// Use `IsSupported()` to check.
class MMAPAllocation : public Allocation {
public:
// Loads and maps the provided file to a memory region.
MMAPAllocation(const char* filename, ErrorReporter* error_reporter);
// Maps the provided file descriptor to a memory region.
// Note: The provided file descriptor will be dup'ed for usage; the caller
// retains ownership of the provided descriptor and should close accordingly.
MMAPAllocation(int fd, ErrorReporter* error_reporter);
virtual ~MMAPAllocation();
const void* base() const override;
size_t bytes() const override;
bool valid() const override;
int fd() const { return mmap_fd_; }
static bool IsSupported();
protected:
// Data required for mmap.
int mmap_fd_ = -1; // mmap file descriptor
const void* mmapped_buffer_;
size_t buffer_size_bytes_ = 0;
private:
// Assumes ownership of the provided `owned_fd` instance.
MMAPAllocation(ErrorReporter* error_reporter, int owned_fd);
};
class FileCopyAllocation : public Allocation {
public:
// Loads the provided file into a heap memory region.
FileCopyAllocation(const char* filename, ErrorReporter* error_reporter);
virtual ~FileCopyAllocation();
const void* base() const override;
size_t bytes() const override;
bool valid() const override;
private:
std::unique_ptr<const char[]> copied_buffer_;
size_t buffer_size_bytes_ = 0;
};
class MemoryAllocation : public Allocation {
public:
// Provides a (read-only) view of the provided buffer region as an allocation.
// Note: The caller retains ownership of `ptr`, and must ensure it remains
// valid for the lifetime of the class instance.
MemoryAllocation(const void* ptr, size_t num_bytes,
ErrorReporter* error_reporter);
virtual ~MemoryAllocation();
const void* base() const override;
size_t bytes() const override;
bool valid() const override;
private:
const void* buffer_;
size_t buffer_size_bytes_ = 0;
};
} // namespace tflite
#endif // TENSORFLOW_LITE_ALLOCATION_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/allocation.h | C++ | apache-2.0 | 3,718 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_ARENA_PLANNER_H_
#define TENSORFLOW_LITE_ARENA_PLANNER_H_
#include <cstdint>
#include <memory>
#include <vector>
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/graph_info.h"
#include "tensorflow/lite/memory_planner.h"
#include "tensorflow/lite/simple_memory_arena.h"
#include "tensorflow/lite/util.h"
namespace tflite {
constexpr const int kDefaultArenaAlignment = 64;
struct AllocationInfo;
// A memory planner that makes all the allocations using arenas.
//
// Before a model is executed by the interpreter, this class determines when
// each tensor needs to be allocated and deallocated, and preallocates all the
// necessary memory (the PlanAllocations phase). It then assigns portions of
// this memory buffer to each tensor (the ExecuteAllocations phase). Tensors may
// share some of the buffer if a tensor B is to be allocated after another
// tensor A has been deallocated.
//
// If dynamic tensors are used the planning steps can be repeated during model
// execution. Since dynamic tensors don't have sizes until after the
// corresponding operation is executed, this class supports incremental
// planning.
class ArenaPlanner : public MemoryPlanner {
public:
// Ownership of 'context' is not taken and it must remain util the
// ArenaPlanner is destroyed. The inputs to the graph will not share
// memory with any other tensor, effectively preserving them until the end
// of inference.
ArenaPlanner(TfLiteContext* context, std::unique_ptr<GraphInfo> graph_info,
bool preserve_all_tensors, int tensor_alignment);
~ArenaPlanner() override;
ArenaPlanner(const ArenaPlanner&) = delete;
ArenaPlanner& operator=(const ArenaPlanner&) = delete;
TfLiteStatus ResetAllocations() override;
TfLiteStatus ResetAllocationsAfter(int node) override;
TfLiteStatus PlanAllocations() override;
TfLiteStatus ExecuteAllocations(int first_node, int last_node) override;
TfLiteStatus ReleaseNonPersistentMemory() override;
TfLiteStatus AcquireNonPersistentMemory() override;
bool HasNonPersistentMemory() override;
// Returns the base arena location for a given allocation type.
std::intptr_t BasePointer(TfLiteAllocationType type);
private:
// Make sure all the arenas have reserved enough memory to store all their
// tensors.
TfLiteStatus Commit();
// Returns vector of tensor number ordered by the following algorithm.
// Comparator to sort tensors for the allocation algorithm:
// - Tensors that have lifespan through the whole model inference time go
// first;
// - Other tensors (e.g. intermediate and temporary ones) are sorted in
// non-increasing order of their size. If sizes of two tensors are equal, the
// one that needs to be allocated earlier goes first.
std::vector<int32_t> CreateTensorAllocationVector(int first_node,
int last_node);
// Traverse the allocation queue and reserve space in the appropriate arena
// for all tensors affected by ops in the interval [first_node, last_node].
TfLiteStatus CalculateAllocations(int first_node, int last_node);
// Assign absolute memory location to a tensor, based on its relative
// position inside the corresponding arena buffer.
TfLiteStatus ResolveTensorAllocation(int tensor_index);
// Register an allocation for all internal (temporary) tensors of
// 'node_index'.
TfLiteStatus CalculateAllocationOfInternalTensors(int node_index);
// Register a deallocation for all internal (temporary) tensors of
// 'node_index'.
TfLiteStatus CalculateDeallocationOfInternalTensors(int node_index);
TfLiteContext* context_;
std::unique_ptr<GraphInfo> graph_info_;
// Stores allocation data for all tensors.
std::vector<ArenaAllocWithUsageInterval> allocs_;
// First node, that uses the tensor. It needs to be allocated before
// execution of the node's operation.
std::vector<int32_t> alloc_node_;
// Last node, that uses the tensor. It can be deallocated after execution of
// the node's operation.
std::vector<int32_t> dealloc_node_;
// Raw memory buffer that is allocated for all temporary and graph outputs
// that are declared kTfLiteArenaRw.
SimpleMemoryArena arena_;
// Raw memory buffer that is allocated for persistent tensors that are
// declared as kTfLiteArenaRwPersistent.
SimpleMemoryArena persistent_arena_;
// If true, then no overlapping of memory areas is done, meaning intermediate
// tensors and temporary tensors can be queried after running.
// (modulo running delegates)
bool preserve_all_tensors_;
// Number of bytes that tensor buffers should be aligned to.
int tensor_alignment_;
};
} // namespace tflite
#endif // TENSORFLOW_LITE_ARENA_PLANNER_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/arena_planner.h | C++ | apache-2.0 | 5,444 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Compatibility shim for new location of interface definitions.
#ifndef TENSORFLOW_LITE_BUILTIN_OP_DATA_H_
#define TENSORFLOW_LITE_BUILTIN_OP_DATA_H_
#include "tensorflow/lite/c/builtin_op_data.h"
#endif // TENSORFLOW_LITE_BUILTIN_OP_DATA_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/builtin_op_data.h | C | apache-2.0 | 916 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_BUILTIN_OPS_H_
#define TENSORFLOW_LITE_BUILTIN_OPS_H_
// DO NOT EDIT MANUALLY: This file is automatically generated by
// `schema/builtin_ops_header/generator.cc`.
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// The enum for builtin operators.
// Note: CUSTOM, DELEGATE, and PLACEHOLDER_FOR_GREATER_OP_CODES are 3 special
// ops which are not real built-in ops.
typedef enum {
kTfLiteBuiltinAdd = 0,
kTfLiteBuiltinAveragePool2d = 1,
kTfLiteBuiltinConcatenation = 2,
kTfLiteBuiltinConv2d = 3,
kTfLiteBuiltinDepthwiseConv2d = 4,
kTfLiteBuiltinDepthToSpace = 5,
kTfLiteBuiltinDequantize = 6,
kTfLiteBuiltinEmbeddingLookup = 7,
kTfLiteBuiltinFloor = 8,
kTfLiteBuiltinFullyConnected = 9,
kTfLiteBuiltinHashtableLookup = 10,
kTfLiteBuiltinL2Normalization = 11,
kTfLiteBuiltinL2Pool2d = 12,
kTfLiteBuiltinLocalResponseNormalization = 13,
kTfLiteBuiltinLogistic = 14,
kTfLiteBuiltinLshProjection = 15,
kTfLiteBuiltinLstm = 16,
kTfLiteBuiltinMaxPool2d = 17,
kTfLiteBuiltinMul = 18,
kTfLiteBuiltinRelu = 19,
kTfLiteBuiltinReluN1To1 = 20,
kTfLiteBuiltinRelu6 = 21,
kTfLiteBuiltinReshape = 22,
kTfLiteBuiltinResizeBilinear = 23,
kTfLiteBuiltinRnn = 24,
kTfLiteBuiltinSoftmax = 25,
kTfLiteBuiltinSpaceToDepth = 26,
kTfLiteBuiltinSvdf = 27,
kTfLiteBuiltinTanh = 28,
kTfLiteBuiltinConcatEmbeddings = 29,
kTfLiteBuiltinSkipGram = 30,
kTfLiteBuiltinCall = 31,
kTfLiteBuiltinCustom = 32,
kTfLiteBuiltinEmbeddingLookupSparse = 33,
kTfLiteBuiltinPad = 34,
kTfLiteBuiltinUnidirectionalSequenceRnn = 35,
kTfLiteBuiltinGather = 36,
kTfLiteBuiltinBatchToSpaceNd = 37,
kTfLiteBuiltinSpaceToBatchNd = 38,
kTfLiteBuiltinTranspose = 39,
kTfLiteBuiltinMean = 40,
kTfLiteBuiltinSub = 41,
kTfLiteBuiltinDiv = 42,
kTfLiteBuiltinSqueeze = 43,
kTfLiteBuiltinUnidirectionalSequenceLstm = 44,
kTfLiteBuiltinStridedSlice = 45,
kTfLiteBuiltinBidirectionalSequenceRnn = 46,
kTfLiteBuiltinExp = 47,
kTfLiteBuiltinTopkV2 = 48,
kTfLiteBuiltinSplit = 49,
kTfLiteBuiltinLogSoftmax = 50,
kTfLiteBuiltinDelegate = 51,
kTfLiteBuiltinBidirectionalSequenceLstm = 52,
kTfLiteBuiltinCast = 53,
kTfLiteBuiltinPrelu = 54,
kTfLiteBuiltinMaximum = 55,
kTfLiteBuiltinArgMax = 56,
kTfLiteBuiltinMinimum = 57,
kTfLiteBuiltinLess = 58,
kTfLiteBuiltinNeg = 59,
kTfLiteBuiltinPadv2 = 60,
kTfLiteBuiltinGreater = 61,
kTfLiteBuiltinGreaterEqual = 62,
kTfLiteBuiltinLessEqual = 63,
kTfLiteBuiltinSelect = 64,
kTfLiteBuiltinSlice = 65,
kTfLiteBuiltinSin = 66,
kTfLiteBuiltinTransposeConv = 67,
kTfLiteBuiltinSparseToDense = 68,
kTfLiteBuiltinTile = 69,
kTfLiteBuiltinExpandDims = 70,
kTfLiteBuiltinEqual = 71,
kTfLiteBuiltinNotEqual = 72,
kTfLiteBuiltinLog = 73,
kTfLiteBuiltinSum = 74,
kTfLiteBuiltinSqrt = 75,
kTfLiteBuiltinRsqrt = 76,
kTfLiteBuiltinShape = 77,
kTfLiteBuiltinPow = 78,
kTfLiteBuiltinArgMin = 79,
kTfLiteBuiltinFakeQuant = 80,
kTfLiteBuiltinReduceProd = 81,
kTfLiteBuiltinReduceMax = 82,
kTfLiteBuiltinPack = 83,
kTfLiteBuiltinLogicalOr = 84,
kTfLiteBuiltinOneHot = 85,
kTfLiteBuiltinLogicalAnd = 86,
kTfLiteBuiltinLogicalNot = 87,
kTfLiteBuiltinUnpack = 88,
kTfLiteBuiltinReduceMin = 89,
kTfLiteBuiltinFloorDiv = 90,
kTfLiteBuiltinReduceAny = 91,
kTfLiteBuiltinSquare = 92,
kTfLiteBuiltinZerosLike = 93,
kTfLiteBuiltinFill = 94,
kTfLiteBuiltinFloorMod = 95,
kTfLiteBuiltinRange = 96,
kTfLiteBuiltinResizeNearestNeighbor = 97,
kTfLiteBuiltinLeakyRelu = 98,
kTfLiteBuiltinSquaredDifference = 99,
kTfLiteBuiltinMirrorPad = 100,
kTfLiteBuiltinAbs = 101,
kTfLiteBuiltinSplitV = 102,
kTfLiteBuiltinUnique = 103,
kTfLiteBuiltinCeil = 104,
kTfLiteBuiltinReverseV2 = 105,
kTfLiteBuiltinAddN = 106,
kTfLiteBuiltinGatherNd = 107,
kTfLiteBuiltinCos = 108,
kTfLiteBuiltinWhere = 109,
kTfLiteBuiltinRank = 110,
kTfLiteBuiltinElu = 111,
kTfLiteBuiltinReverseSequence = 112,
kTfLiteBuiltinMatrixDiag = 113,
kTfLiteBuiltinQuantize = 114,
kTfLiteBuiltinMatrixSetDiag = 115,
kTfLiteBuiltinRound = 116,
kTfLiteBuiltinHardSwish = 117,
kTfLiteBuiltinIf = 118,
kTfLiteBuiltinWhile = 119,
kTfLiteBuiltinNonMaxSuppressionV4 = 120,
kTfLiteBuiltinNonMaxSuppressionV5 = 121,
kTfLiteBuiltinScatterNd = 122,
kTfLiteBuiltinSelectV2 = 123,
kTfLiteBuiltinDensify = 124,
kTfLiteBuiltinSegmentSum = 125,
kTfLiteBuiltinBatchMatmul = 126,
kTfLiteBuiltinPlaceholderForGreaterOpCodes = 127,
kTfLiteBuiltinCumsum = 128,
kTfLiteBuiltinCallOnce = 129,
kTfLiteBuiltinBroadcastTo = 130,
kTfLiteBuiltinRfft2d = 131,
kTfLiteBuiltinConv3d = 132,
kTfLiteBuiltinImag = 133,
kTfLiteBuiltinReal = 134,
kTfLiteBuiltinComplexAbs = 135,
kTfLiteBuiltinHashtable = 136,
kTfLiteBuiltinHashtableFind = 137,
kTfLiteBuiltinHashtableImport = 138,
kTfLiteBuiltinHashtableSize = 139,
kTfLiteBuiltinReduceAll = 140,
} TfLiteBuiltinOperator;
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TENSORFLOW_LITE_BUILTIN_OPS_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/builtin_ops.h | C | apache-2.0 | 5,722 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_C_BUILTIN_OP_DATA_H_
#define TENSORFLOW_LITE_C_BUILTIN_OP_DATA_H_
#include <stdint.h>
#include "tensorflow/lite/c/common.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// TfLiteReshapeParams can't have dynamic data so we fix the maximum possible
// number of dimensions.
#define TFLITE_RESHAPE_PARAMS_MAX_DIMENSION_COUNT 8
// TODO(aselle): Consider using "if this then that" for testing.
// Useful placeholder to put in otherwise empty structs to avoid size warnings.
typedef struct {
char dummy;
} EmptyStructPlaceholder;
// IMPORTANT: All new members of structs must be added at the end to ensure
// backwards compatibility.
// Possible padding types (for convolutions)
typedef enum {
kTfLitePaddingUnknown = 0,
kTfLitePaddingSame,
kTfLitePaddingValid,
} TfLitePadding;
typedef enum {
kTfLiteMirrorPaddingUnknown = 0,
kTfLiteMirrorPaddingReflect,
kTfLiteMirrorPaddingSymmetric,
} TfLiteMirrorPaddingMode;
// TODO(b/130259536): We should move this out of builtin_op_data.
typedef struct {
int width;
int height;
int width_offset;
int height_offset;
} TfLitePaddingValues;
typedef struct {
TfLiteMirrorPaddingMode mode;
} TfLiteMirrorPaddingParams;
// Possible fused activation functions.
typedef enum {
kTfLiteActNone = 0,
kTfLiteActRelu,
kTfLiteActReluN1To1, // min(max(-1, x), 1)
kTfLiteActRelu6, // min(max(0, x), 6)
kTfLiteActTanh,
kTfLiteActSignBit,
kTfLiteActSigmoid,
} TfLiteFusedActivation;
typedef struct {
// Parameters for CONV_2D version 1.
TfLitePadding padding;
int stride_width;
int stride_height;
TfLiteFusedActivation activation;
// Parameters for CONV_2D version 2.
// Note: Version 2 supports dilation values not equal to 1.
int dilation_width_factor;
int dilation_height_factor;
} TfLiteConvParams;
typedef struct {
TfLitePadding padding;
int stride_width;
int stride_height;
int stride_depth;
int dilation_width_factor;
int dilation_height_factor;
int dilation_depth_factor;
TfLiteFusedActivation activation;
} TfLiteConv3DParams;
typedef struct {
TfLitePadding padding;
int stride_width;
int stride_height;
int filter_width;
int filter_height;
TfLiteFusedActivation activation;
struct {
TfLitePaddingValues padding;
} computed;
} TfLitePoolParams;
typedef struct {
// Parameters for DepthwiseConv version 1 or above.
TfLitePadding padding;
int stride_width;
int stride_height;
// `depth_multiplier` is redundant. It's used by CPU kernels in
// TensorFlow 2.0 or below, but ignored in versions above.
//
// The information can be deduced from the shape of input and the shape of
// weights. Since the TFLiteConverter toolchain doesn't support partially
// specified shapes, relying on `depth_multiplier` stops us from supporting
// graphs with dynamic shape tensors.
//
// Note: Some of the delegates (e.g. NNAPI, GPU) are still relying on this
// field.
int depth_multiplier;
TfLiteFusedActivation activation;
// Parameters for DepthwiseConv version 2 or above.
int dilation_width_factor;
int dilation_height_factor;
} TfLiteDepthwiseConvParams;
typedef struct {
int rank;
TfLiteFusedActivation activation;
// Parameter for SVDF version 4.
bool asymmetric_quantize_inputs;
} TfLiteSVDFParams;
typedef struct {
TfLiteFusedActivation activation;
// Parameter for RNN version 3.
bool asymmetric_quantize_inputs;
} TfLiteRNNParams;
typedef struct {
bool time_major;
TfLiteFusedActivation activation;
// Parameter for Sequence RNN version 3.
bool asymmetric_quantize_inputs;
} TfLiteSequenceRNNParams;
typedef struct {
bool time_major;
TfLiteFusedActivation activation;
bool merge_outputs;
// Parameter for Bidirectional RNN verison 3.
bool asymmetric_quantize_inputs;
} TfLiteBidirectionalSequenceRNNParams;
typedef enum {
kTfLiteFullyConnectedWeightsFormatDefault = 0,
kTfLiteFullyConnectedWeightsFormatShuffled4x16Int8 = 1,
} TfLiteFullyConnectedWeightsFormat;
typedef struct {
// Parameters for FullyConnected version 1 or above.
TfLiteFusedActivation activation;
// Parameters for FullyConnected version 2 or above.
TfLiteFullyConnectedWeightsFormat weights_format;
// Parameters for FullyConnected version 5 or above.
// If set to true, then the number of dimensions in the input and the output
// tensors are the same. Furthermore, all but the last dimension of the input
// and output shapes will be equal.
bool keep_num_dims;
// Parameters for FullyConnected version 7 or above.
// If set to true and the weights are quantized, then non constant inputs
// are quantized at evaluation time with asymmetric quantization.
bool asymmetric_quantize_inputs;
} TfLiteFullyConnectedParams;
typedef enum {
kTfLiteLshProjectionUnknown = 0,
kTfLiteLshProjectionSparse = 1,
kTfLiteLshProjectionDense = 2,
} TfLiteLSHProjectionType;
typedef struct {
TfLiteLSHProjectionType type;
} TfLiteLSHProjectionParams;
typedef struct {
float beta;
} TfLiteSoftmaxParams;
typedef struct {
int axis;
TfLiteFusedActivation activation;
} TfLiteConcatenationParams;
typedef struct {
TfLiteFusedActivation activation;
// Parameter added for the version 4.
bool pot_scale_int16;
} TfLiteAddParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLiteSpaceToBatchNDParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLiteBatchToSpaceNDParams;
typedef struct {
bool adj_x;
bool adj_y;
// Parameters for BatchMatMul version 4 or above.
// If set to true and the weights are quantized, then non constant inputs
// are quantized at evaluation time with asymmetric quantization.
bool asymmetric_quantize_inputs;
} TfLiteBatchMatMulParams;
typedef struct {
TfLiteFusedActivation activation;
} TfLiteMulParams;
typedef struct {
TfLiteFusedActivation activation;
// Parameter added for the version 5.
bool pot_scale_int16;
} TfLiteSubParams;
typedef struct {
TfLiteFusedActivation activation;
} TfLiteDivParams;
typedef struct {
TfLiteFusedActivation activation;
} TfLiteL2NormParams;
typedef struct {
int radius;
float bias;
float alpha;
float beta;
} TfLiteLocalResponseNormParams;
typedef enum {
kTfLiteLSTMFullKernel = 0,
kTfLiteLSTMBasicKernel
} TfLiteLSTMKernelType;
typedef struct {
// Parameters for LSTM version 1.
TfLiteFusedActivation activation;
float cell_clip;
float proj_clip;
// Parameters for LSTM version 2.
// kTfLiteLSTMBasicKernel is only supported in version 2 or above.
TfLiteLSTMKernelType kernel_type;
// Parameters for LSTM version 4.
bool asymmetric_quantize_inputs;
} TfLiteLSTMParams;
typedef struct {
// Parameters needed for the underlying LSTM.
TfLiteFusedActivation activation;
float cell_clip;
float proj_clip;
// If set to true then the first dimension is time, otherwise batch.
bool time_major;
// Parameter for unidirectional sequence RNN version 3.
bool asymmetric_quantize_inputs;
} TfLiteUnidirectionalSequenceLSTMParams;
typedef struct {
// Parameters supported by version 1:
// Parameters inherited for the LSTM kernel.
TfLiteFusedActivation activation;
float cell_clip;
float proj_clip;
// If true, store the outputs of both directions in the first output.
bool merge_outputs;
// Parameters supported by version 2:
// If set to true then the first dimension is time, otherwise batch.
bool time_major;
// Parameters supported by version 4:
// If set to true, then hybrid ops use asymmetric quantization for inputs.
bool asymmetric_quantize_inputs;
} TfLiteBidirectionalSequenceLSTMParams;
typedef struct {
bool align_corners;
// half_pixel_centers assumes pixels are of half the actual dimensions, and
// yields more accurate resizes. Corresponds to the same argument for the
// original TensorFlow op in TF2.0.
bool half_pixel_centers;
} TfLiteResizeBilinearParams;
typedef struct {
bool align_corners;
bool half_pixel_centers;
} TfLiteResizeNearestNeighborParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLitePadParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLitePadV2Params;
typedef struct {
// These fields are only used in old models for backward compatibility.
// In the current implementation, we use the 2nd input of the op as the shape,
// and these fields are unused.
int shape[TFLITE_RESHAPE_PARAMS_MAX_DIMENSION_COUNT];
int num_dimensions;
} TfLiteReshapeParams;
typedef struct {
int ngram_size;
int max_skip_size;
bool include_all_ngrams;
} TfLiteSkipGramParams;
typedef struct {
int block_size;
} TfLiteSpaceToDepthParams;
typedef struct {
int block_size;
} TfLiteDepthToSpaceParams;
typedef struct {
TfLiteType in_data_type;
TfLiteType out_data_type;
} TfLiteCastParams;
typedef enum {
kTfLiteCombinerTypeSum = 0,
kTfLiteCombinerTypeMean = 1,
kTfLiteCombinerTypeSqrtn = 2,
} TfLiteCombinerType;
typedef struct {
TfLiteCombinerType combiner;
} TfLiteEmbeddingLookupSparseParams;
typedef struct {
int axis;
int batch_dims;
} TfLiteGatherParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLiteTransposeParams;
typedef struct {
bool keep_dims;
} TfLiteReducerParams;
typedef struct {
int num_splits;
} TfLiteSplitParams;
typedef struct {
int num_splits;
} TfLiteSplitVParams;
typedef struct {
// TODO(ahentz): We can't have dynamic data in this struct, at least not yet.
// For now we will fix the maximum possible number of dimensions.
int squeeze_dims[8];
int num_squeeze_dims;
} TfLiteSqueezeParams;
typedef struct {
int begin_mask;
int end_mask;
int ellipsis_mask;
int new_axis_mask;
int shrink_axis_mask;
} TfLiteStridedSliceParams;
typedef struct {
TfLiteType output_type;
} TfLiteArgMaxParams;
typedef struct {
TfLiteType output_type;
} TfLiteArgMinParams;
typedef struct {
TfLitePadding padding;
int stride_width;
int stride_height;
} TfLiteTransposeConvParams;
typedef struct {
bool validate_indices;
} TfLiteSparseToDenseParams;
typedef struct {
TfLiteType out_type;
} TfLiteShapeParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLiteRankParams;
typedef struct {
// Parameters supported by version 1:
float min;
float max;
int num_bits;
// Parameters supported by version 2:
bool narrow_range;
} TfLiteFakeQuantParams;
typedef struct {
int values_count;
int axis;
} TfLitePackParams;
typedef struct {
int axis;
} TfLiteOneHotParams;
typedef struct {
int num;
int axis;
} TfLiteUnpackParams;
typedef struct {
float alpha;
} TfLiteLeakyReluParams;
typedef struct {
TfLiteType index_out_type;
} TfLiteUniqueParams;
typedef struct {
int seq_dim;
int batch_dim;
} TfLiteReverseSequenceParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLiteMatrixDiagParams;
typedef struct {
EmptyStructPlaceholder placeholder;
} TfLiteMatrixSetDiagParams;
typedef struct {
int then_subgraph_index;
int else_subgraph_index;
} TfLiteIfParams;
typedef struct {
int cond_subgraph_index;
int body_subgraph_index;
} TfLiteWhileParams;
typedef struct {
bool exclusive;
bool reverse;
} TfLiteCumsumParams;
typedef struct {
int init_subgraph_index;
} TfLiteCallOnceParams;
typedef struct {
int table_id;
TfLiteType key_dtype;
TfLiteType value_dtype;
} TfLiteHashtableParams;
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TENSORFLOW_LITE_C_BUILTIN_OP_DATA_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/c/builtin_op_data.h | C | apache-2.0 | 12,169 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_C_C_API_H_
#define TENSORFLOW_LITE_C_C_API_H_
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
#include "tensorflow/lite/c/c_api_types.h" // IWYU pragma: export
// --------------------------------------------------------------------------
/// C API for TensorFlow Lite.
///
/// The API leans towards simplicity and uniformity instead of convenience, as
/// most usage will be by language-specific wrappers. It provides largely the
/// same set of functionality as that of the C++ TensorFlow Lite `Interpreter`
/// API, but is useful for shared libraries where having a stable ABI boundary
/// is important.
///
/// Conventions:
/// * We use the prefix TfLite for everything in the API.
/// * size_t is used to represent byte sizes of objects that are
/// materialized in the address space of the calling process.
/// * int is used as an index into arrays.
///
/// Usage:
/// <pre><code>
/// // Create the model and interpreter options.
/// TfLiteModel* model = TfLiteModelCreateFromFile("/path/to/model.tflite");
/// TfLiteInterpreterOptions* options = TfLiteInterpreterOptionsCreate();
/// TfLiteInterpreterOptionsSetNumThreads(options, 2);
///
/// // Create the interpreter.
/// TfLiteInterpreter* interpreter = TfLiteInterpreterCreate(model, options);
///
/// // Allocate tensors and populate the input tensor data.
/// TfLiteInterpreterAllocateTensors(interpreter);
/// TfLiteTensor* input_tensor =
/// TfLiteInterpreterGetInputTensor(interpreter, 0);
/// TfLiteTensorCopyFromBuffer(input_tensor, input.data(),
/// input.size() * sizeof(float));
///
/// // Execute inference.
/// TfLiteInterpreterInvoke(interpreter);
///
/// // Extract the output tensor data.
/// const TfLiteTensor* output_tensor =
// TfLiteInterpreterGetOutputTensor(interpreter, 0);
/// TfLiteTensorCopyToBuffer(output_tensor, output.data(),
/// output.size() * sizeof(float));
///
/// // Dispose of the model and interpreter objects.
/// TfLiteInterpreterDelete(interpreter);
/// TfLiteInterpreterOptionsDelete(options);
/// TfLiteModelDelete(model);
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
// --------------------------------------------------------------------------
// Opaque types used by the C API.
// TfLiteModel wraps a loaded TensorFlow Lite model.
typedef struct TfLiteModel TfLiteModel;
// TfLiteInterpreterOptions allows customized interpreter configuration.
typedef struct TfLiteInterpreterOptions TfLiteInterpreterOptions;
// Allows delegation of nodes to alternative backends.
typedef struct TfLiteDelegate TfLiteDelegate;
// TfLiteInterpreter provides inference from a provided model.
typedef struct TfLiteInterpreter TfLiteInterpreter;
// A tensor in the interpreter system which is a wrapper around a buffer of
// data including a dimensionality (or NULL if not currently defined).
typedef struct TfLiteTensor TfLiteTensor;
// --------------------------------------------------------------------------
// TfLiteVersion returns a string describing version information of the
// TensorFlow Lite library. TensorFlow Lite uses semantic versioning.
TFL_CAPI_EXPORT extern const char* TfLiteVersion(void);
// Returns a model from the provided buffer, or null on failure.
TFL_CAPI_EXPORT extern TfLiteModel* TfLiteModelCreate(const void* model_data,
size_t model_size);
// Returns a model from the provided file, or null on failure.
TFL_CAPI_EXPORT extern TfLiteModel* TfLiteModelCreateFromFile(
const char* model_path);
// Destroys the model instance.
TFL_CAPI_EXPORT extern void TfLiteModelDelete(TfLiteModel* model);
// Returns a new interpreter options instances.
TFL_CAPI_EXPORT extern TfLiteInterpreterOptions*
TfLiteInterpreterOptionsCreate();
// Destroys the interpreter options instance.
TFL_CAPI_EXPORT extern void TfLiteInterpreterOptionsDelete(
TfLiteInterpreterOptions* options);
// Sets the number of CPU threads to use for the interpreter.
TFL_CAPI_EXPORT extern void TfLiteInterpreterOptionsSetNumThreads(
TfLiteInterpreterOptions* options, int32_t num_threads);
// Adds a delegate to be applied during `TfLiteInterpreter` creation.
//
// If delegate application fails, interpreter creation will also fail with an
// associated error logged.
//
// NOTE: The caller retains ownership of the delegate and should ensure that it
// remains valid for the duration of any created interpreter's lifetime.
TFL_CAPI_EXPORT extern void TfLiteInterpreterOptionsAddDelegate(
TfLiteInterpreterOptions* options, TfLiteDelegate* delegate);
// Sets a custom error reporter for interpreter execution.
//
// * `reporter` takes the provided `user_data` object, as well as a C-style
// format string and arg list (see also vprintf).
// * `user_data` is optional. If provided, it is owned by the client and must
// remain valid for the duration of the interpreter lifetime.
TFL_CAPI_EXPORT extern void TfLiteInterpreterOptionsSetErrorReporter(
TfLiteInterpreterOptions* options,
void (*reporter)(void* user_data, const char* format, va_list args),
void* user_data);
// Returns a new interpreter using the provided model and options, or null on
// failure.
//
// * `model` must be a valid model instance. The caller retains ownership of the
// object, and can destroy it immediately after creating the interpreter; the
// interpreter will maintain its own reference to the underlying model data.
// * `optional_options` may be null. The caller retains ownership of the object,
// and can safely destroy it immediately after creating the interpreter.
//
// NOTE: The client *must* explicitly allocate tensors before attempting to
// access input tensor data or invoke the interpreter.
TFL_CAPI_EXPORT extern TfLiteInterpreter* TfLiteInterpreterCreate(
const TfLiteModel* model, const TfLiteInterpreterOptions* optional_options);
// Destroys the interpreter.
TFL_CAPI_EXPORT extern void TfLiteInterpreterDelete(
TfLiteInterpreter* interpreter);
// Returns the number of input tensors associated with the model.
TFL_CAPI_EXPORT extern int32_t TfLiteInterpreterGetInputTensorCount(
const TfLiteInterpreter* interpreter);
// Returns the tensor associated with the input index.
// REQUIRES: 0 <= input_index < TfLiteInterpreterGetInputTensorCount(tensor)
TFL_CAPI_EXPORT extern TfLiteTensor* TfLiteInterpreterGetInputTensor(
const TfLiteInterpreter* interpreter, int32_t input_index);
// Resizes the specified input tensor.
//
// NOTE: After a resize, the client *must* explicitly allocate tensors before
// attempting to access the resized tensor data or invoke the interpreter.
// REQUIRES: 0 <= input_index < TfLiteInterpreterGetInputTensorCount(tensor)
TFL_CAPI_EXPORT extern TfLiteStatus TfLiteInterpreterResizeInputTensor(
TfLiteInterpreter* interpreter, int32_t input_index, const int* input_dims,
int32_t input_dims_size);
// Updates allocations for all tensors, resizing dependent tensors using the
// specified input tensor dimensionality.
//
// This is a relatively expensive operation, and need only be called after
// creating the graph and/or resizing any inputs.
TFL_CAPI_EXPORT extern TfLiteStatus TfLiteInterpreterAllocateTensors(
TfLiteInterpreter* interpreter);
// Runs inference for the loaded graph.
//
// Before calling this function, the caller should first invoke
// TfLiteInterpreterAllocateTensors() and should also set the values for the
// input tensors. After successfully calling this function, the values for the
// output tensors will be set.
//
// NOTE: It is possible that the interpreter is not in a ready state to
// evaluate (e.g., if AllocateTensors() hasn't been called, or if a
// ResizeInputTensor() has been performed without a subsequent call to
// AllocateTensors()).
//
// If the (experimental!) delegate fallback option was enabled in the
// interpreter options, then the interpreter will automatically fall back to
// not using any delegates if execution with delegates fails. For details, see
// TfLiteInterpreterOptionsSetEnableDelegateFallback in c_api_experimental.h.
//
// Returns one of the following status codes:
// - kTfLiteOk: Success. Output is valid.
// - kTfLiteDelegateError: Execution with delegates failed, due to a problem
// with the delegate(s). If fallback was not enabled, output is invalid.
// If fallback was enabled, this return value indicates that fallback
// succeeded, the output is valid, and all delegates previously applied to
// the interpreter have been undone.
// - kTfLiteApplicationError: Same as for kTfLiteDelegateError, except that
// the problem was not with the delegate itself, but rather was
// due to an incompatibility between the delegate(s) and the
// interpreter or model.
// - kTfLiteError: Unexpected/runtime failure. Output is invalid.
TFL_CAPI_EXPORT extern TfLiteStatus TfLiteInterpreterInvoke(
TfLiteInterpreter* interpreter);
// Returns the number of output tensors associated with the model.
TFL_CAPI_EXPORT extern int32_t TfLiteInterpreterGetOutputTensorCount(
const TfLiteInterpreter* interpreter);
// Returns the tensor associated with the output index.
// REQUIRES: 0 <= output_index < TfLiteInterpreterGetOutputTensorCount(tensor)
//
// NOTE: The shape and underlying data buffer for output tensors may be not
// be available until after the output tensor has been both sized and allocated.
// In general, best practice is to interact with the output tensor *after*
// calling TfLiteInterpreterInvoke().
TFL_CAPI_EXPORT extern const TfLiteTensor* TfLiteInterpreterGetOutputTensor(
const TfLiteInterpreter* interpreter, int32_t output_index);
// --------------------------------------------------------------------------
// TfLiteTensor wraps data associated with a graph tensor.
//
// Note that, while the TfLiteTensor struct is not currently opaque, and its
// fields can be accessed directly, these methods are still convenient for
// language bindings. In the future the tensor struct will likely be made opaque
// in the public API.
// Returns the type of a tensor element.
TFL_CAPI_EXPORT extern TfLiteType TfLiteTensorType(const TfLiteTensor* tensor);
// Returns the number of dimensions that the tensor has.
TFL_CAPI_EXPORT extern int32_t TfLiteTensorNumDims(const TfLiteTensor* tensor);
// Returns the length of the tensor in the "dim_index" dimension.
// REQUIRES: 0 <= dim_index < TFLiteTensorNumDims(tensor)
TFL_CAPI_EXPORT extern int32_t TfLiteTensorDim(const TfLiteTensor* tensor,
int32_t dim_index);
// Returns the size of the underlying data in bytes.
TFL_CAPI_EXPORT extern size_t TfLiteTensorByteSize(const TfLiteTensor* tensor);
// Returns a pointer to the underlying data buffer.
//
// NOTE: The result may be null if tensors have not yet been allocated, e.g.,
// if the Tensor has just been created or resized and `TfLiteAllocateTensors()`
// has yet to be called, or if the output tensor is dynamically sized and the
// interpreter hasn't been invoked.
TFL_CAPI_EXPORT extern void* TfLiteTensorData(const TfLiteTensor* tensor);
// Returns the (null-terminated) name of the tensor.
TFL_CAPI_EXPORT extern const char* TfLiteTensorName(const TfLiteTensor* tensor);
// Returns the parameters for asymmetric quantization. The quantization
// parameters are only valid when the tensor type is `kTfLiteUInt8` and the
// `scale != 0`. Quantized values can be converted back to float using:
// real_value = scale * (quantized_value - zero_point);
TFL_CAPI_EXPORT extern TfLiteQuantizationParams TfLiteTensorQuantizationParams(
const TfLiteTensor* tensor);
// Copies from the provided input buffer into the tensor's buffer.
// REQUIRES: input_data_size == TfLiteTensorByteSize(tensor)
TFL_CAPI_EXPORT extern TfLiteStatus TfLiteTensorCopyFromBuffer(
TfLiteTensor* tensor, const void* input_data, size_t input_data_size);
// Copies to the provided output buffer from the tensor's buffer.
// REQUIRES: output_data_size == TfLiteTensorByteSize(tensor)
TFL_CAPI_EXPORT extern TfLiteStatus TfLiteTensorCopyToBuffer(
const TfLiteTensor* output_tensor, void* output_data,
size_t output_data_size);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TENSORFLOW_LITE_C_C_API_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/c/c_api.h | C | apache-2.0 | 13,036 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_C_C_API_EXPERIMENTAL_H_
#define TENSORFLOW_LITE_C_C_API_EXPERIMENTAL_H_
#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/c/c_api.h"
#include "tensorflow/lite/c/common.h"
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
/// Resets all variable tensors to zero.
///
/// WARNING: This is an experimental API and subject to change.
TFL_CAPI_EXPORT extern TfLiteStatus TfLiteInterpreterResetVariableTensors(
TfLiteInterpreter* interpreter);
/// Adds an op registration for a builtin operator.
///
/// Op registrations are used to map ops referenced in the flatbuffer model
/// to executable function pointers (`TfLiteRegistration`s).
///
/// NOTE: The interpreter will make a shallow copy of `registration` internally,
/// so the caller should ensure that its contents (function pointers, etc...)
/// remain valid for the duration of the interpreter's lifetime. A common
/// practice is making the provided `TfLiteRegistration` instance static.
///
/// Code that uses this function should NOT call
/// `TfLiteInterpreterOptionsSetOpResolver' on the same options object.
///
/// WARNING: This is an experimental API and subject to change.
TFL_CAPI_EXPORT void TfLiteInterpreterOptionsAddBuiltinOp(
TfLiteInterpreterOptions* options, TfLiteBuiltinOperator op,
const TfLiteRegistration* registration, int32_t min_version,
int32_t max_version);
/// Adds an op registration for a custom operator.
///
/// Op registrations are used to map ops referenced in the flatbuffer model
/// to executable function pointers (`TfLiteRegistration`s).
///
/// NOTE: The interpreter will make a shallow copy of `registration` internally,
/// so the caller should ensure that its contents (function pointers, etc...)
/// remain valid for the duration of any created interpreter's lifetime. A
/// common practice is making the provided `TfLiteRegistration` instance static.
///
/// Code that uses this function should NOT call
/// `TfLiteInterpreterOptionsSetOpResolver' on the same options object.
///
/// WARNING: This is an experimental API and subject to change.
TFL_CAPI_EXPORT void TfLiteInterpreterOptionsAddCustomOp(
TfLiteInterpreterOptions* options, const char* name,
const TfLiteRegistration* registration, int32_t min_version,
int32_t max_version);
/// Registers callbacks for resolving builtin or custom operators.
///
/// The `TfLiteInterpreterOptionsSetOpResolver` function provides an alternative
/// method for registering builtin ops and/or custom ops, by providing operator
/// resolver callbacks. Unlike using `TfLiteInterpreterOptionsAddBuiltinOp`
/// and/or `TfLiteInterpreterOptionsAddAddCustomOp`, these let you register all
/// the operators in a single call.
///
/// Code that uses this function should NOT call
/// `TfLiteInterpreterOptionsAddBuiltin' or
/// `TfLiteInterpreterOptionsAddCustomOp' on the same options object.
///
/// WARNING: This is an experimental API and subject to change.
void TfLiteInterpreterOptionsSetOpResolver(
TfLiteInterpreterOptions* options,
const TfLiteRegistration* (*find_builtin_op)(void* user_data,
TfLiteBuiltinOperator op,
int version),
const TfLiteRegistration* (*find_custom_op)(void* user_data,
const char* custom_op,
int version),
void* op_resolver_user_data);
/// Returns a new interpreter using the provided model and options, or null on
/// failure, where the model uses only the operators explicitly added to the
/// options. This is the same as `TFLiteInterpreterCreate` from `c_api.h`,
/// except that the only operators that are supported are the ones registered
/// in `options` via calls to `TfLiteInterpreterOptionsSetOpResolver`,
/// `TfLiteInterpreterOptionsAddBuiltinOp`, and/or
/// `TfLiteInterpreterOptionsAddCustomOp`.
///
/// * `model` must be a valid model instance. The caller retains ownership of
/// the object, and can destroy it immediately after creating the interpreter;
/// the interpreter will maintain its own reference to the underlying model
/// data.
/// * `options` should not be null. The caller retains ownership of the object,
/// and can safely destroy it immediately after creating the interpreter.
///
/// NOTE: The client *must* explicitly allocate tensors before attempting to
/// access input tensor data or invoke the interpreter.
///
/// WARNING: This is an experimental API and subject to change.
TFL_CAPI_EXPORT extern TfLiteInterpreter*
TfLiteInterpreterCreateWithSelectedOps(const TfLiteModel* model,
const TfLiteInterpreterOptions* options);
/// Enable or disable the NN API delegate for the interpreter (true to enable).
///
/// WARNING: This is an experimental API and subject to change.
TFL_CAPI_EXPORT extern void TfLiteInterpreterOptionsSetUseNNAPI(
TfLiteInterpreterOptions* options, bool enable);
/// Enable or disable CPU fallback for the interpreter (true to enable).
/// If enabled, TfLiteInterpreterInvoke will do automatic fallback from
/// executing with delegate(s) to regular execution without delegates
/// (i.e. on CPU).
///
/// Allowing the fallback is suitable only if both of the following hold:
/// - The caller is known not to cache pointers to tensor data across
/// TfLiteInterpreterInvoke calls.
/// - The model is not stateful (no variables, no LSTMs) or the state isn't
/// needed between batches.
///
/// When delegate fallback is enabled, TfLiteInterpreterInvoke will
/// behave as follows:
/// If one or more delegates were set in the interpreter options
/// (see TfLiteInterpreterOptionsAddDelegate),
/// AND inference fails,
/// then the interpreter will fall back to not using any delegates.
/// In that case, the previously applied delegate(s) will be automatically
/// undone, and an attempt will be made to return the interpreter to an
/// invokable state, which may invalidate previous tensor addresses,
/// and the inference will be attempted again, using input tensors with
/// the same value as previously set.
///
/// WARNING: This is an experimental API and subject to change.
TFL_CAPI_EXPORT extern void TfLiteInterpreterOptionsSetEnableDelegateFallback(
TfLiteInterpreterOptions* options, bool enable);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // TENSORFLOW_LITE_C_C_API_EXPERIMENTAL_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/c/c_api_experimental.h | C | apache-2.0 | 7,191 |
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_C_C_API_INTERNAL_H_
#define TENSORFLOW_LITE_C_C_API_INTERNAL_H_
#include <stdarg.h>
#include <memory>
#include <vector>
#include "tensorflow/lite/builtin_ops.h"
#include "tensorflow/lite/core/api/error_reporter.h"
#include "tensorflow/lite/core/api/op_resolver.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/mutable_op_resolver.h"
// Internal structures and subroutines used by the C API. These are likely to
// change and should not be depended on directly by any C API clients.
//
// NOTE: This header does not follow C conventions and does not define a C API.
// It is effectively an (internal) implementation detail of the C API.
struct TfLiteModel {
// Sharing is safe as FlatBufferModel is const.
std::shared_ptr<const tflite::FlatBufferModel> impl;
};
// The `TfLiteOpResolver` struct is an abstract callback interface that
// contains function pointers for callbacks that return a
// `TfLiteRegistration` given an op code or custom op name. This mechanism is
// used to map ops referenced in the flatbuffer model to executable function
// pointers (`TfLiteRegistration`s).
// This struct mirrors the tflite::OpResolver C++ abstract base class.
struct TfLiteOpResolverCallbacks {
// Opaque data that gets passed down to the callback functions.
void* user_data = nullptr;
// Callback that finds the op registration for a builtin operator by enum
// code. The `user_data` parameter will be set to the
// `op_resolver_user_data` value that was passed to
// `TfLiteInterpreterOptionsSetOpResolver`.
const TfLiteRegistration* (*find_builtin_op)(void* user_data,
TfLiteBuiltinOperator op,
int version);
// Callback that finds the op registration of a custom operator by op name.
// The `user_data` parameter will be set to the `op_resolver_user_data` value
// that was passed to `TfLiteInterpreterOptionsSetOpResolver`.
const TfLiteRegistration* (*find_custom_op)(void* user_data, const char* op,
int version);
};
// This struct mirrors the tflite::ErrorResolver C++ abstract base class.
struct TfLiteErrorReporterCallback {
// Opaque data that gets passed down to the callback function.
void* user_data = nullptr;
// Callback function that reports an error.
void (*error_reporter)(void* user_data, const char* format,
va_list args) = nullptr;
};
struct TfLiteInterpreterOptions {
enum {
kDefaultNumThreads = -1,
};
int num_threads = kDefaultNumThreads;
tflite::MutableOpResolver mutable_op_resolver;
TfLiteOpResolverCallbacks op_resolver_callbacks = {};
std::vector<TfLiteDelegate*> delegates;
TfLiteErrorReporterCallback error_reporter_callback;
bool use_nnapi = false;
// Determines whether to allow automatic fallback to CPU.
// If true, and if one or more delegates were set,
// then if Invoke with delegates fails, it will be
// automatically retried without delegates.
bool enable_delegate_fallback = false;
};
struct TfLiteInterpreter {
// Taking a reference to the (const) model data avoids lifetime-related issues
// and complexity with the TfLiteModel's existence.
std::shared_ptr<const tflite::FlatBufferModel> model;
// The interpreter does not take ownership of the provided ErrorReporter
// instance, so we ensure its validity here. Note that the interpreter may use
// the reporter in its destructor, so the reporter should be declared first.
std::unique_ptr<tflite::ErrorReporter> optional_error_reporter;
std::unique_ptr<tflite::Interpreter> impl;
bool enable_delegate_fallback;
};
namespace tflite {
namespace internal {
// This adds the builtin and/or custom operators specified in options in
// `optional_options` (if any) to `mutable_resolver`, and then returns a newly
// created TfLiteInterpreter using `mutable_op_resolver` as the default
// OpResolver, and using any other options in `optional_options`, and using
// the provided `model`.
//
// * `model` must be a valid model instance. The caller retains ownership of the
// object, and can destroy it immediately after creating the interpreter; the
// interpreter will maintain its own reference to the underlying model data.
// * `optional_options` may be null. The caller retains ownership of the object,
// and can safely destroy it immediately after creating the interpreter.
// * `mutable_resolver` must not be null. The caller retains ownership of the
// MutableOpResolver object, and can safely destroy it immediately after
// creating the interpreter.
//
// NOTE: The client *must* explicitly allocate tensors before attempting to
// access input tensor data or invoke the interpreter.
TfLiteInterpreter* InterpreterCreateWithOpResolver(
const TfLiteModel* model, const TfLiteInterpreterOptions* optional_options,
tflite::MutableOpResolver* mutable_resolver);
} // namespace internal
} // namespace tflite
#endif // TENSORFLOW_LITE_C_C_API_INTERNAL_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/c/c_api_internal.h | C++ | apache-2.0 | 5,784 |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This file declares types used by the pure C inference API defined in c_api.h,
// some of which are also used in the C++ and C kernel and interpreter APIs.
#ifndef TENSORFLOW_LITE_C_C_API_TYPES_H_
#define TENSORFLOW_LITE_C_C_API_TYPES_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
// Define TFL_CAPI_EXPORT macro to export a function properly with a shared
// library.
#ifdef SWIG
#define TFL_CAPI_EXPORT
#elif defined(TFL_STATIC_LIBRARY_BUILD)
#define TFL_CAPI_EXPORT
#else // not definded TFL_STATIC_LIBRARY_BUILD
#if defined(_WIN32)
#ifdef TFL_COMPILE_LIBRARY
#define TFL_CAPI_EXPORT __declspec(dllexport)
#else
#define TFL_CAPI_EXPORT __declspec(dllimport)
#endif // TFL_COMPILE_LIBRARY
#else
#define TFL_CAPI_EXPORT __attribute__((visibility("default")))
#endif // _WIN32
#endif // SWIG
typedef enum TfLiteStatus {
kTfLiteOk = 0,
// Generally referring to an error in the runtime (i.e. interpreter)
kTfLiteError = 1,
// Generally referring to an error from a TfLiteDelegate itself.
kTfLiteDelegateError = 2,
// Generally referring to an error in applying a delegate due to
// incompatibility between runtime and delegate, e.g., this error is returned
// when trying to apply a TfLite delegate onto a model graph that's already
// immutable.
kTfLiteApplicationError = 3
} TfLiteStatus;
// Types supported by tensor
typedef enum {
kTfLiteNoType = 0,
kTfLiteFloat32 = 1,
kTfLiteInt32 = 2,
kTfLiteUInt8 = 3,
kTfLiteInt64 = 4,
kTfLiteString = 5,
kTfLiteBool = 6,
kTfLiteInt16 = 7,
kTfLiteComplex64 = 8,
kTfLiteInt8 = 9,
kTfLiteFloat16 = 10,
kTfLiteFloat64 = 11,
kTfLiteComplex128 = 12,
kTfLiteUInt64 = 13,
kTfLiteResource = 14,
kTfLiteVariant = 15,
kTfLiteUInt32 = 16,
} TfLiteType;
// Legacy. Will be deprecated in favor of TfLiteAffineQuantization.
// If per-layer quantization is specified this field will still be populated in
// addition to TfLiteAffineQuantization.
// Parameters for asymmetric quantization. Quantized values can be converted
// back to float using:
// real_value = scale * (quantized_value - zero_point)
typedef struct TfLiteQuantizationParams {
float scale;
int32_t zero_point;
} TfLiteQuantizationParams;
#ifdef __cplusplus
} // extern C
#endif
#endif // TENSORFLOW_LITE_C_C_API_TYPES_H_
| YifuLiu/AliOS-Things | components/ai_agent/src/engine/tflite-micro/tensorflow/lite/c/c_api_types.h | C | apache-2.0 | 2,981 |